1

可以编译以下代码:

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)

为什么?

4

2 回答 2

6

我会说 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的函数,您可以作为参数传递。UnitTTIntfUnitInt() => 12

于 2014-08-24T16:15:43.527 回答
0

只是因为和...=> 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)将按预期工作

于 2014-08-24T16:52:33.267 回答