本文介绍了多个参数的隐式转换的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在Scala中对一组参数(而不将它们定义为某些类成员)实现隐式转换,例如

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)

推荐答案

可能:

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

自然,在生成的 val 上必须有一个类型注释,以驱动隐式转换的搜索和应用.

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

附录

在我看来,还有另一种方式不涉及可疑的隐式转换:

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

这篇关于多个参数的隐式转换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-22 07:11