例如,如何编写隐式应用以下内容的表达式:
implicit def intsToString(x: Int, y: Int) = "test"
val s: String = ... //?
Run Code Online (Sandbox Code Playgroud)
谢谢
ret*_*nym 18
一个参数的隐式函数用于自动将值转换为期望的类型.这些被称为隐式视图.有两个论点,它不起作用或有意义.
您可以将隐式视图应用于TupleN:
implicit def intsToString( xy: (Int, Int)) = "test"
val s: String = (1, 2)
Run Code Online (Sandbox Code Playgroud)
您还可以将任何函数的最终参数列表标记为隐式.
def intsToString(implicit x: Int, y: Int) = "test"
implicit val i = 0
val s: String = intsToString
Run Code Online (Sandbox Code Playgroud)
或者,将以下两种用法结合起来implicit:
implicit def intsToString(implicit x: Int, y: Int) = "test"
implicit val i = 0
val s: String = implicitly[String]
Run Code Online (Sandbox Code Playgroud)
然而,在这种情况下它并没有真正有用.
UPDATE
要详细说明马丁的评论,这是可能的.
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]
Run Code Online (Sandbox Code Playgroud)