我有一个构造函数,它接受一个主参数(数据)和另一个参数(模型),它具有合理的默认初始化,这取决于主参数.
我希望有可能在适当的时候为模型赋予另一个值.
一个简化的例子:
1)没有默认参数:
class trainer(data:Int,model:Double) {}
2)初始化:
def init(data:Int): Double = 1.0/data
3)如果初始化独立于其他参数,它将起作用:
class trainer(data:Int,model:Double = init(1)) {}
4)我想拥有什么,但是什么给出了错误:
class trainer(data:Int,model:Double = init(data)) {}
实现我想做的最好/最接近的方式是什么?
解决方法
你可以简单地重载一下构造函数:
class Trainer(data:Int,model:Double) { def this(data:Int) = this(data,init(data)) }
然后你可以实例化使用:
new Trainer(4) new Trainer(4,5.0)
另一种方法是使用具有不同应用重载的伴随对象:
//optionally make the constructor protected or private,so the only way to instantiate is using the companion object class Trainer private(data:Int,model:Double) object Trainer { def apply(data:Int,model:Double) = new Trainer(data,model) def apply(data:Int) = new Trainer(data,init(data)) }
然后你可以实例化使用
Trainer(4) Trainer(4,5.0)
另一种方法是使用默认值为None的Option,然后在类体中初始化一个私有变量:
class Trainer(data:Int,model:Option[Double] = None) { val modelValue = model.getOrElse(init(data)) }
然后使用以下方法实例化:
new Trainer(5) new Trainer(5,Some(4.0))