11

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

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

val s: String = ... //?

谢谢

4

2 回答 2

18

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

您可以将隐式视图应用于 a 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]
于 2010-03-10T12:49:26.693 回答
4

Jason 的回答遗漏了一个非常重要的情况:一个具有多个参数的隐式函数,其中除了第一个参数之外的所有参数都是隐式的……这需要两个参数列表,但考虑到问题的表达方式,这似乎并没有超出范围。

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

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
于 2011-05-15T15:35:26.133 回答