Implicit conversion for multiple parameters

青春壹個敷衍的年華 提交于 2021-01-29 15:07:10

问题


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)

回答1:


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


来源:https://stackoverflow.com/questions/20290630/implicit-conversion-for-multiple-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!