首页 文章

Scala构造函数重载?

提问于
浏览
123

你如何在Scala中提供重载的构造函数?

6 回答

  • 173

    值得明确提到的是,Scala中的辅助构造函数必须调用主构造函数(如在landon9720中)或同一类中的另一个辅助构造函数作为它们的第一个操作 . 它们不能像Java那样简单地或者隐式地调用超类的构造函数 . 这可确保主构造函数是该类的唯一入口点 .

    class Foo(x: Int, y: Int, z: String) {  
      // default y parameter to 0  
      def this(x: Int, z: String) = this(x, 0, z)   
      // default x & y parameters to 0
      // calls previous auxiliary constructor which calls the primary constructor  
      def this(z: String) = this(0, z);   
    }
    
  • 29
    class Foo(x: Int, y: Int) {
         def this(x: Int) = this(x, 0) // default y parameter to 0
     }
    
  • 15

    从Scala 2.8.0开始,您还可以使用构造函数和方法参数的默认值 . 像这样

    scala> class Foo(x:Int, y:Int = 0, z:Int=0) {                           
         | override def toString() = { "Foo(" + x + ", " + y + ", " + z + ")" }
         | }
    defined class Foo
    
    scala> new Foo(1, 2, 3)                                                    
    res0: Foo = Foo(1, 2, 3)
    
    scala> new Foo(4)                                                          
    res1: Foo = Foo(4, 0, 0)
    

    具有默认值的参数必须位于参数列表中没有默认值的参数之后 .

  • 1

    在查看我的代码时,我突然意识到我做了一个重载构造函数 . 然后我想起了那个问题并回来给出了另一个答案:

    在Scala中,您不能重载构造函数,但可以使用函数执行此操作 .

    此外,许多人选择将伴侣对象的 apply 功能作为相应类的工厂 .

    使这个类抽象并重载 apply 函数来实现 - 实例化这个类,你有你的重载“构造函数”:

    abstract class Expectation[T] extends BooleanStatement {
        val expected: Seq[T]
        …
    }
    
    object Expectation {
        def apply[T](expd:     T ): Expectation[T] = new Expectation[T] {val expected = List(expd)}
        def apply[T](expd: Seq[T]): Expectation[T] = new Expectation[T] {val expected =      expd }
    
        def main(args: Array[String]): Unit = {
            val expectTrueness = Expectation(true)
            …
        }
    }
    

    请注意,我明确定义每个 apply 以返回 Expectation[T] ,否则它将返回一个鸭型 Expectation[T]{val expected: List[T]} .

  • 8

    我想可能是Scala Constructors(2008-11-11)可以添加更多信息 .

  • 0

    试试这个

    class A(x: Int, y: Int) {
      def this(x: Int) = this(x, x)
      def this() = this(1)
      override def toString() = "x=" + x + " y=" + y
      class B(a: Int, b: Int, c: String) {
        def this(str: String) = this(x, y, str)
        override def toString() =
          "x=" + x + " y=" + y + " a=" + a + " b=" + b + " c=" + c
      }
    }
    

相关问题