例如,如何编写隐式应用以下内容的表达式:
implicit def intsToString(x: Int, y: Int) = "test"
val s: String = ... //?
由于
答案 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