可以编译以下代码:
def hello[T](f: => T) = f
hello(() => 12)
但不跟随:
def hello(f: => Int) = f
hello(() => 12)
哪个报告错误:
<console>:9: error: type mismatch;
found : () => Int
required: Int
hello(() => 12)
为什么?
可以编译以下代码:
def hello[T](f: => T) = f
hello(() => 12)
但不跟随:
def hello(f: => Int) = f
hello(() => 12)
哪个报告错误:
<console>:9: error: type mismatch;
found : () => Int
required: Int
hello(() => 12)
为什么?
我会说 becauseT
可以是 any () => x
,但Int
不能是 a () => x
。
在您的情况下,您将() => 12
作为参数传递,这是一种合法的行为,因为T
没有约束并且可以是任何东西,实际上这样做会返回一个部分应用的函数:
scala> def hello[T](f: => T) = f
hello: [T](f: => T)T
scala> hello(()=>12)
res1: () => Int = <function0>
你可以这样称呼:
scala> res1()
res2: Int = 12
第二种情况相反,您将一个函数传递给该函数,Unit
该函数Int
不是一个Int
(它返回一个Int
但它不是一个Int
)。
作为按名称参数调用传递的事实f
在这里没有任何区别:
scala> def hello[T](f: T) = f
hello: [T](f: T)T
scala> hello(()=>12)
res11: () => Int = <function0>
scala> def hello(f: Int) = f
hello: (f: Int)Int
scala> hello(()=>12)
<console>:9: error: type mismatch;
found : () => Int
required: Int
hello(()=>12)
不要混淆 this:f: => T
和 this: f: () => T
,它们是不同的东西,要清楚:
scala> def hello[T](f: () => T) = f
hello: [T](f: () => T)() => T
scala> hello(()=>12)
res13: () => Int = <function0>
scala> def hello(f: () => Int) = f
hello: (f: () => Int)() => Int
scala> hello(()=>12)
res14: () => Int = <function0>
现在它在两种情况下都可以编译,因为在第一种情况下是 from tof
的函数(当然可以是 an ),在第二种情况下是 from to的函数,您可以作为参数传递。Unit
T
T
Int
f
Unit
Int
() => 12
只是因为和...=> T
不一样() => T
=> T
是叫名字,意思是
def hello(f: => Int) = f
应该这样称呼:
hello(12)
def hello[T](f: => T) = f
起作用的原因() => 12
是因为你Function0[Int]
在 T 的位置上放了一个,这与仅仅一个Int
要使() =>
语法按预期工作,请考虑这样做:
def hello(f: () => Int) = f // can also be written as:
def hello(f: Function0[Int]) = f
现在,您的函数需要a Function0
,以前没有,并且hello(() => 12)
将按预期工作