【问题标题】:Overload constructor for Scala's Case Classes?Scala案例类的重载构造函数?
【发布时间】:2011-01-24 22:34:17
【问题描述】:

在 Scala 2.8 中有没有办法重载案例类的构造函数?

如果是,请放一个sn-p解释,如果不是,请解释原因?

【问题讨论】:

    标签: scala constructor overloading scala-2.8 case-class


    【解决方案1】:

    您可以按照通常的方式定义一个重载的构造函数,但要调用它,您必须使用“new”关键字。

    scala> case class A(i: Int) { def this(s: String) = this(s.toInt) }
    defined class A
    
    scala> A(1)
    res0: A = A(1)
    
    scala> A("2")
    <console>:8: error: type mismatch;
     found   : java.lang.String("2")
     required: Int
           A("2")
             ^
    
    scala> new A("2")
    res2: A = A(2)
    

    【讨论】:

    • 严格来说这不是真的——你可以在伴生对象中像往常一样声明它
    【解决方案2】:

    重载构造函数对于案例类并不特殊:

    case class Foo(bar: Int, baz: Int) {
      def this(bar: Int) = this(bar, 0)
    }
    
    new Foo(1, 2)
    new Foo(1)
    

    但是,您可能还希望在伴随对象中重载 apply 方法,当您省略 new 时会调用该方法。

    object Foo {
      def apply(bar: Int) = new Foo(bar)
    }
    
    Foo(1, 2)
    Foo(1)
    

    在 Scala 2.8 中,通常可以使用命名参数和默认参数来代替重载。

    case class Baz(bar: Int, baz: Int = 0)
    new Baz(1)
    Baz(1)
    

    【讨论】:

    • 非常好 :) 我在 scala 中寻找类似后备值的东西,它是 2.8 的新内容吗?我不知道:)
    • 是的,命名和默认参数是 Scala 2.8 中的新参数。
    • Martin Odersky 解释了为什么没有自动添加其他应用方法:scala-lang.org/node/976
    • 我如何在重载的构造函数中使用局部变量?例如:def this(bar: Int) = { val test = 0; this(bar,test) }(这是行不通的)
    • 二级构造函数
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-10
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 2013-12-30
    • 1970-01-01
    相关资源
    最近更新 更多