Question

Is it possible to implement in Scala an implicit conversion for the group of parameters (without defining them as some class member) like

implicit def triple2One (x :Int, s :String, d :Double) =  x  // just as an example

So that I would be able to call it in the code like

val x :Int = (1, "test", 2.0)
Was it helpful?

Solution

It is possible:

scala> implicit def iFromISD(isd: (Int, String, Double)): Int = isd._1
iFromISD: (isd: (Int, String, Double))Int

scala> val x: Int = (1, "two", 3.0)
x: Int = 1

Naturally, there has to be a type annotation on the resulting val to drive the search for and application of the implicit conversion.

Addendum

It occurs to me there's another way that doesn't involve dubious implicit conversions:

scala> val (y, _, _) = (1, "two", 3.0)
y: Int = 1
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top