1

我找不到在 scala 中做类似事情的自然方法:

class Car {
  var speed: Int
  var color: String
}

var myCar = new Car()

myCar.set {
  speed = 5
  color = "green"
}

我知道在 Groovy 等其他语言中也是可能的。我也知道我可以用这样的构造函数来做到这一点:

val myCar = new Car { 
  speed = 5
  color = "green"
}

我对做同样事情的方法感兴趣,不是在对象构造上,而是在稍后,一旦对象已经创建

这就是我迄今为止一直在做的事情:

class Car (var speed: Int, var color: String) {

  def set(f: (Car) => Unit) = {
    f(this)
  }

}

val myCar = new Car(5, "red")
myCar.set { c =>
  c.speed = 12
  c.color = "green"
}

但我不喜欢为每个属性编写 'c' var

关于我该怎么做或者是否有更简单的方法的任何想法?

4

3 回答 3

2

除非绝对必要,否则应避免使用可变类。您通常会在 Scala 中执行此操作:

case class Car(speed: Int, color: String)

val c1 = Car(5, "red")
val c2 = c1.copy(speed = 12, color = "green")

(然后c2是新版本的汽车,而c1保持不变。)


如果你想坚持你的可变类型,为什么不只是

class Car(var speed: Int, var color: String)

val myCar = new Car(5, "red")
import myCar._
speed = 12
color = "green"

使用专用set方法:

class Car(var speed: Int, var color: String) {
  def set(speed: Int = this.speed, color: String = this.color): Unit = {
    this.speed = speed
    this.color = color
  }
}

val myCar = new Car(5, "red")
myCar.set(speed = 12, color = "green")
myCar.set(color = "blue")
于 2013-08-30T14:36:48.653 回答
1

Although we all agree to say var reassignement is ugly, this is a possible solution

object DoTo { 
  def apply[T](that: T)(functions: (T) => Unit*): T = {
    functions foreach { _.apply(that) }
    that
  }    
}


class Car (var speed: Int, var color: String) {
  def move() = println("moving")
  def stop() = println("stop")
}


val myNewCar = DoTo(new Car(12, "red")) (
  _.move(),
  _.stop(),
  _.speed = 15,
  _.color = "green"
)

This is not exactly what I wanted initially but I cannot find anything simpler whithout using macros :-(

于 2013-09-05T08:45:36.140 回答
1

您可以通过导入变量来做到这一点:

class Car {
  var speed: Int = _
  var color: String = _
}

// ...
val myCar = new Car();
// a blocks that works with myCar:
{
    import myCar._
    // access the content without any prefix
    speed = 5
    color = "green"
}
于 2013-09-05T11:25:36.227 回答