不同函数创建之间的区别是什么?



这个问题与我的另一个问题密切相关(并且可能导致我解决那个问题),但肯定是不同的。

如何允许传入a =>任意ref函数并调用该函数

我一直在玩不同的函数创建,坦率地说,我在创建类型=> AnyRef和=> String的匿名函数时遇到了麻烦。我想我可以创建一个类型为()=> AnyRef和()=> String的函数。

示例1我有以下代码

def debugLazyTest2(msg: => String) : Unit = {
  System.out.println(msg)
}
//and client code
  val function: () => String = () => {
    executed = true
    "asdf"+executed+" hi there"
  }
  log2.debugLazyTest2(function)

但是编译错误显示found: () => String这是有意义的,但是然后显示"required: String"而不是"required: => String"

这是怎么回事?

例子2变得更奇怪,我有这段代码编译而上面没有编译

def debugLazyTest(msg: => AnyRef) : Unit = {
  System.out.println(msg.toString)
}
//and client code which compiles!!!!
  val function: () => AnyRef = () => {
    executed = true
    "asdf"+executed+" hi there"
  }
  log2.debugLazyTest(function)

这段代码编译,虽然它不工作的方式,我想库似乎不能调用toString之前调用函数(这是在我的另一个线程,是一个单独的问题)。

你知道这是怎么回事吗?

谢谢,院长

如果你这样写,它会工作的:

log2.debugLazyTest2(function())

msg是按名称的形参,而不是函数。你必须传入一个String类型的表达式(或者第二个例子中的AnyRef)

第二个示例之所以编译,是因为您传入的()=> AnyRef实际上也是一个AnyRef,因为函数是一个AnyRef。但是,打印的是函数本身,而不是执行它的结果。

考虑以下代码:

scala> def test(x: String) = debugLazyTest2(x)
test: (x: String)Unit

如果我们运行(在Scala 2.11.2中):

:javap test

并修剪一些生成的输出,我们看到如下:

  public void test(java.lang.String);
    flags: ACC_PUBLIC
    Code:
      stack=4, locals=2, args_size=2
         0: getstatic     #19                 // Field .MODULE$:L;
         3: new           #21                 // class $anonfun$test$1
         6: dup
         7: aload_1
         8: invokespecial #23                 // Method $anonfun$test$1."<init>":(Ljava/lang/String;)V
        11: invokevirtual #27                 // Method .debugLazyTest2:(Lscala/Function0;)V
        14: return
      LocalVariableTable:
        Start  Length  Slot  Name   Signature
               0      15     0  this   L;
               0      15     1     x   Ljava/lang/String;
      LineNumberTable:
        line 8: 0

然后考虑debugLazyTest2的签名:

 public void debugLazyTest2(scala.Function0<java.lang.String>);

关键行是:

         3: new           #21                 // class $anonfun$test$1

如果我正确阅读代码,我们正在实例化类$anonfun$test$1的新实例-并将新的匿名Function0[String]传递给debugLazyTest2。这使得我们的test方法等价于以下内容:

def test(x: String) = debugLazyTest2(new Function0[String] {
    def apply(): String = x
})

当我们考虑将Function0[String]的实例传递给debugLazyTest2进行相同的转换时,我们得到:

debugLazyTest2(function)
变成了

:

debugLazyTest2(new Function0[String] {
    def apply(): Function0[String] = function
})

当然不能编译,因为apply(): Function0[String]不匹配所需的类型apply(): String(因此出现错误消息)。

实际上调用函数而不是返回它是有效的:

debugLazyTest2(function())

就变成:

debugLazyTest2(new Function0[String] {
    def apply(): String = function()
})

相关内容

最新更新