scala - How can I specify multiple constructors in the case class? -
i'm trying create case class multiple constructors:
object app { def main(args: array[string]) { val = 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! -- imposible invoke outside class def this(b: boolean, x: int, y: int) { this("", 0, (i: int) => % x + y == 0) } */ }
so far code doesn't work:
error:(10, 23) type mismatch; found : boolean(true) required: string val b = something(true, 10, 20) ^
to fix need create companion object hold apply function represents new constructor something
class:
object { def apply(b: boolean, x: int, y: int) = { new something(if (b) "" else "default", 0, _ => { (x + y) % 2 == 0 }) } }
it inconvenient. maybe there other way place multiple constructors case class?
actually works, have use new
auxiliary constructors not have apply
generated case class:
case class something(s: string, n: int, p: int => boolean) { def this(b: boolean, x: int, y: int) { this("", 0, (i: int) => % x + y == 0) } } new something(true, 5, 5) // works
if want something(true, 5, 5)
work, need create companion object said. think because otherwise case class won't able work pattern matching now, or have been more complicated. , notice pattern matching won't work in case
also remember case class supports default constructors case class something(s: string = "default")
might you, not fix example unfortunately
Comments
Post a Comment