Search code examples
scalaimplicit

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?


Solution

  • 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)