加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 综合聚焦 > 服务器 > 安全 > 正文

scala:可选的默认参数作为其他参数的函数

发布时间:2020-12-16 18:08:19 所属栏目:安全 来源:网络整理
导读:我有一个构造函数,它接受一个主参数(数据)和另一个参数(模型),它具有合理的默认初始化,这取决于主参数. 我希望有可能在适当的时候为模型赋予另一个值. 一个简化的例子: 1)没有默认参数: class trainer(data:Int,model:Double) {} 2)初始化: def init(data
我有一个构造函数,它接受一个主参数(数据)和另一个参数(模型),它具有合理的默认初始化,这取决于主参数.

我希望有可能在适当的时候为模型赋予另一个值.

一个简化的例子:

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))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读