Scala 构造带或不带参数的对象
Scala construct objects with or without arguments
在 Scala 中,需要一个 class 如果调用其无参数构造函数,它将根据预定义的计算构造一个默认对象(下面的代码在语法上可能不正确,但显示了想法)。我将能够通过使用 this(i, s)
和在外部创建的参数创建一个对象来测试它的方法。最好的方法是什么?
class myobj(i: Int, s: String) {
def this() = {
val j = 7 // in reality more computation with extra vals involved
val i = j
val str = "abcdefg"
val s = str.get(indexOf (i % 5))
this(i, s)
}
}
使用静态工厂可能会更好:
class MyObj(i: Int, s: String)
object MyObj {
def apply() = {
val j = 7 // in reality more computation with extra vals involved
val i = j
val str = "abcdefg"
val s = ""
new MyObj(i, s)
}
}
那么你可以这样做:
val o = MyObj()
在 Scala 中,需要一个 class 如果调用其无参数构造函数,它将根据预定义的计算构造一个默认对象(下面的代码在语法上可能不正确,但显示了想法)。我将能够通过使用 this(i, s)
和在外部创建的参数创建一个对象来测试它的方法。最好的方法是什么?
class myobj(i: Int, s: String) {
def this() = {
val j = 7 // in reality more computation with extra vals involved
val i = j
val str = "abcdefg"
val s = str.get(indexOf (i % 5))
this(i, s)
}
}
使用静态工厂可能会更好:
class MyObj(i: Int, s: String)
object MyObj {
def apply() = {
val j = 7 // in reality more computation with extra vals involved
val i = j
val str = "abcdefg"
val s = ""
new MyObj(i, s)
}
}
那么你可以这样做:
val o = MyObj()