简体   繁体   中英

Can I have an implicit conversion method in a Scala case class?

Is it possible to have a method in a class that does implicit conversions. In this case I want to be able to instantly unpack a an object which represents a pair of things into a 2-tuple.

case class Foo(a:String, b:String) {
  implicit def asTuple:(String, String) = (a,b)
}
val foo0 = new Foo("Hello", "World")

// Does not work!
val (a:String, b:String) = foo0

The example above is broken.

Here's my 2nd attempt - also broken:

class Foo(a:String, b:String) {
  val _a:String = a
  val _b:String = b
}

implicit def asTuple(x:Foo):(String, String) = (x._a, x._b)

val foo0 = new Foo("Hello", "World")

// Does not work!
val (a:String, b:String) = foo0

Given that I've managed to make implicit type conversions from one class into another 'just work', I expect that what's going wrong here is more to do with the definition of the tuple as a return type. Can anybody help me out?

Your first example doesn't work because you have to define the implicit in the companion object or in an other scope as you've done with the second example. The second example doesn't seem to work because Scala isn't able to do pattern matching and implicit conversion in one step. Instead, change the last line to one of the following to make it work:

val (a:String, b:String): (String, String) = foo0

or

val (a: String, b: String) = foo0: (String, String)

The reason this doesn't work is that = with a pattern on the left-hand side, as in your examples, is exactly equivalent to

foo0 match {
  case (a: String, b: String) => 
    // the rest of the body
}

(and will throw MatchError if the match doesn't succeed).

Scala type inference works left-to-right, so it works out foo0 first, and there is no expected type to trigger the implicit conversion. And only then it sees that the pattern can't possibly match the type.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM