如何在Scala中使用多个输入的含义?

时间:2010-03-10 12:15:53

标签: scala implicit

例如,如何编写隐式应用以下内容的表达式:

implicit def intsToString(x: Int, y: Int) = "test"

val s: String = ... //?

由于

2 个答案:

答案 0 :(得分:18)

一个参数的隐式函数用于自动将值转换为期望的类型。这些被称为隐式视图。有两个论点,它不起作用或有意义。

您可以将隐式视图应用于TupleN

implicit def intsToString( xy: (Int, Int)) = "test"
val s: String = (1, 2)

您还可以将任何函数的最终参数列表标记为隐式。

def intsToString(implicit x: Int, y: Int) = "test"
implicit val i = 0
val s: String = intsToString

或者,结合implicit的这两种用法:

implicit def intsToString(implicit x: Int, y: Int) = "test"
implicit val i = 0
val s: String = implicitly[String]

然而,在这种情况下它并没有用。

<强>更新

详细说明马丁的评论,这是可能的。

implicit def foo(a: Int, b: Int) = 0
// ETA expansion results in:
// implicit val fooFunction: (Int, Int) => Int = (a, b) => foo(a, b)

implicitly[(Int, Int) => Int]

答案 1 :(得分:4)

杰森的回答错过了一个非常重要的案例:一个带有多个参数的隐式函数,其中除了第一个之外的所有参数都是隐含的......这需要两个参数列表,但这似乎没有超出范围给出问题的方式表达了。

这是一个带有两个参数的隐式转换的例子,

case class Foo(s : String)
case class Bar(i : Int)

implicit val defaultBar = Bar(23)

implicit def fooIsInt(f : Foo)(implicit b : Bar) = f.s.length+b.i

示例REPL会话,

scala> case class Foo(s : String)
defined class Foo

scala> case class Bar(i : Int)
defined class Bar

scala> implicit val defaultBar = Bar(23)
defaultBar: Bar = Bar(23)

scala> implicit def fooIsInt(f : Foo)(implicit b : Bar) = f.s.length+b.i
fooIsInt: (f: Foo)(implicit b: Bar)Int

scala> val i : Int = Foo("wibble")
i: Int = 29