多次后期初始化 [英] Multiple late initialisation
问题描述
我找不到在scala中执行类似操作的自然方法:
I could not find a natural way to do something like that in scala :
class Car {
var speed: Int
var color: String
}
var myCar = new Car()
myCar.set {
speed = 5
color = "green"
}
我知道在Groovy等其他语言中也是可能的.我也知道我可以用这样的构造函数来做到这一点:
I know it is possible in other languages as Groovy. I also know I can do it with a constructor like this :
val myCar = new Car {
speed = 5
color = "green"
}
我感兴趣的是这样做的一种方法,而不是在对象构造时,而是在对象创建完成之后,
I am interested in a way to do the same, not at the object construction but later, once the object has already been created
这是我到目前为止所做的:
This is what I have been doing so far :
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'变量
But I do not like the need to write the 'c' var for every attribute
关于如何操作或是否有更简单方法的任何想法??
Any idea on how I can do it or if there is an easier way ??
推荐答案
除非绝对必要,否则应避免使用可变的类.您通常会在Scala中执行此操作:
You should avoid mutable classes unless absolutely necessary. You would do normally this in Scala:
case class Car(speed: Int, color: String)
val c1 = Car(5, "red")
val c2 = c1.copy(speed = 12, color = "green")
(然后 c2
是汽车的新版本,而 c1
保持不变.)
(Then c2
is a new version of the car, while c1
remains unchanged.)
如果您想坚持使用可变类型,为什么不这么做
If you want to stick with your mutable type, why not just
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")
这篇关于多次后期初始化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!