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

scala – 如何在case类中指定多个构造函数?

发布时间:2020-12-16 09:08:17 所属栏目:安全 来源:网络整理
导读:我正在尝试创建一个包含多个构造函数的case类: object App { def main(args: Array[String]) { val a = Something("abc",100500,_ % 2 == 0) val b = Something(true,10,20) println(s"$a - $b") }}case class Something(s: String,n: Int,p: Int = Boolean
我正在尝试创建一个包含多个构造函数的case类:

object App {
  def main(args: Array[String]) {
    val a = Something("abc",100500,_ % 2 == 0)
    val b = Something(true,10,20)   
    println(s"$a - $b")
  }
}

case class Something(s: String,n: Int,p: Int => Boolean) {
  /*
  Additional constructor -- Wrong way! -- it is imposible to invoke it outside the class
  def this(b: Boolean,x: Int,y: Int) {
    this("",(i: Int) => i % x + y == 0)
  }
  */
}

到目前为止我的代码不起作用:

Error:(10,23) type mismatch;
 found   : Boolean(true)
 required: String
    val b = Something(true,20)
                      ^

要修复它,我需要创建一个伴随对象来保存一个apply函数,该函数表示Something类的新构造函数:

object Something {    
  def apply(b: Boolean,y: Int) = {
    new Something(if (b) "" else "default",_ => {
      (x + y) % 2 == 0
    })
  }   
}

这很不方便.也许还有其他方法可以将多个构造函数放入case类中?

解决方法

实际上它可以工作,但你必须使用new作为辅助构造函数,没有为case类生成apply:

case class Something(s: String,p: Int => Boolean) {
  def this(b: Boolean,(i: Int) => i % x + y == 0)
  }
}

new Something(true,5,5) // Works

如果你想要Something(true,5)工作,你需要像你说的那样创建伴侣对象.我认为这是因为否则案例类将无法像现在一样处理模式匹配,或者它会更加复杂.并注意在这种情况下模式匹配不起作用

还要记住case类支持默认构造函数,例如case类Something(s:String =“default”),这可能对你有所帮助,但它不能解决你的例子

(编辑:李大同)

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

    推荐文章
      热点阅读