Overload constructor for Scala's Case Classes?

后端 未结 2 1234
轮回少年
轮回少年 2020-12-01 02:46

In Scala 2.8 is there a way to overload constructors of a case class?

If yes, please put a snippet to explain, if not, please explain why?

2条回答
  •  北荒
    北荒 (楼主)
    2020-12-01 03:15

    You can define an overloaded constructor the usual way, but to invoke it you have to use the "new" keyword.

    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")
    :8: error: type mismatch;
     found   : java.lang.String("2")
     required: Int
           A("2")
             ^
    
    scala> new A("2")
    res2: A = A(2)
    

提交回复
热议问题