所以我有一个特征,我需要有具体的成员变量。不过,通过init方法为这些变量赋值。所以,当我声明它们时,我必须将它们赋值为null。另一种选择是使用None,但是我必须将它们声明为OptionT,这也是我不想要的。
所以,我的问题是,我可以在Scala中声明一个尚未赋值的var既不为null也不为None吗?
发布于 2019-04-17 21:39:50
我的第一个尝试是使用abstract class
abstract class Test(arg1: Int, arg2: String) {
val calculatedInConstructor1 = ??? // use args here
val calculatedInConstructor2 = ??? // use args here
}
new Test(1, "test") {}如果由于某种原因这是不可能的,那么我仍然可以使用这样的东西来实现:
trait Test {
// have to be provided in implementation
protected val arg1: Int
protected val arg2: String
// lazy will defer initialization so you can provide
// arg1 and arg2 in class extending Test
lazy val calculatedOnFirstUse1 = ??? // use args here
lazy val calculatedOnFirstUse2 = ??? // use args here
}
new Test {
val arg1 = 1
val arg2 = "test"
}没有理由使用var%s、null%s等。
发布于 2019-04-17 22:12:48
您可以将它们定义为方法:
trait Test {
def arg1: Int
def arg2: String
}
val x=new Test {
def arg1=1
def arg2 = "test"
}您也可以重写为val
val y=new Test {
val arg1=2
val arg2="test2"
}
val z= new Test{
val arg1=3 // won't compile
}
x.arg1
x.arg2
y.arg1
y.arg2https://stackoverflow.com/questions/55728712
复制相似问题