Can I have an implicit conversion method in a Scala case class? -
is possible have method in class implicit conversions. in case want able instantly unpack object represents pair of things 2-tuple.
case class foo(a:string, b:string) { implicit def astuple:(string, string) = (a,b) } val foo0 = new foo("hello", "world") // not work! val (a:string, b:string) = foo0
the example above broken.
here's 2nd attempt - broken:
class foo(a:string, b:string) { val _a:string = val _b:string = b } implicit def astuple(x:foo):(string, string) = (x._a, x._b) val foo0 = new foo("hello", "world") // not work! val (a:string, b:string) = foo0
given i've managed make implicit type conversions 1 class 'just work', expect what's going wrong here more definition of tuple return type. can me out?
your first example doesn't work because have define implicit in companion object or in other scope you've done second example. second example doesn't seem work because scala isn't able pattern matching , implicit conversion in 1 step. instead, change last line 1 of following make work:
val (a:string, b:string): (string, string) = foo0
or
val (a: string, b: string) = foo0: (string, string)
Comments
Post a Comment