Any to Function的隐式def将apply方法添加到类中

Knu*_*daa 2 scala

看看以下内容,看看你是否能够理解它:

Welcome to Scala version 2.8.1.final (Java HotSpot(TM) Client VM, Java 1.6.0_17).
Type in expressions to have them evaluated.
Type :help for more information.

scala> class A
defined class A

scala> val a = new A
a: A = A@1643e4b

scala> a.apply("foo")
<console>:8: error: value apply is not a member of A
       a.apply("foo")
         ^
Run Code Online (Sandbox Code Playgroud)

到目前为止看起来完全正常.但后来我们添加了隐式转换.

scala> implicit def anyToFunc(any: Any) = { x: String => "bar" }
anyToFunc: (any: Any)(String) => java.lang.String

scala> a.apply("foo")
res1: java.lang.String = bar
Run Code Online (Sandbox Code Playgroud)

并且突然A有一个apply方法接受一个与隐式返回的函数相同类型的参数!

让我们再检查一下:

scala> class B { override def toString = "an instance of class B" }
defined class B

scala> implicit def anyToFunc(any: Any) = { x: String =>
     | println("any is " + any.toString)
     | println("x is " + x)
     | "bar" }
anyToFunc: (any: Any)(String) => java.lang.String

scala> val b = new B
b: B = an instance of class B

scala> b.apply("test")
any is an instance of class B
x is test
res8: java.lang.String = bar
Run Code Online (Sandbox Code Playgroud)

这是一个"隐藏的功能"吗?如果是这样,它的用途是什么?

sep*_*p2k 5

你正在调用apply一个类型的对象A.A没有apply方法.但是A可以隐式转换为Function[String, String],它确实有一个apply方法.因此,应用隐式转换并apply在转换的对象上调用.

这个功能没有任何魔力或隐藏.如果一个对象没有你正在调用它的方法,但是可以隐式转换为一个对象,那么它将被转换.这正是隐式转换的用途.