Scala constructor overload?

前端 未结 5 1425
栀梦
栀梦 2020-11-27 15:27

How do you provide overloaded constructors in Scala?

5条回答
  •  一生所求
    2020-11-27 15:53

    While looking at my code, I suddenly realized that I did kind of an overload a constructor. I then remembered that question and came back to give another answer:

    In Scala, you can’t overload constructors, but you can do this with functions.

    Also, many choose to make the apply function of a companion object a factory for the respective class.

    Making this class abstract and overloading the apply function to implement-instantiate this class, you have your overloaded “constructor”:

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

    Note that I explicitly define each apply to return Expectation[T], else it would return a duck-typed Expectation[T]{val expected: List[T]}.

提交回复
热议问题