Scala函数评估

时间:2015-01-30 17:18:01

标签: scala

在下面的代码中:

object typeparam {

  val v = new MyClass[Int]                        //> v  : typeparam.MyClass[Int] = typeparam$MyClass@17943a4

  def f1(a : Int) = {
    println("f here")

    3
  }                                               //> f1: (a: Int)Int

  v.foreach2(f1)                                  //> foreach2

  class MyClass[A] {

    def foreach2[B](f: B => A) = {
      println("foreach2")
      f
    }

  }

}

为什么在函数foreach2中没有调用函数f1?

如果我改为使用

object typeparam {

  val v = new MyClass[Int]                        //> v  : typeparam.MyClass[Int] = typeparam$MyClass@14fe5c

  def f1() = {
    println("f here")
  }                                               //> f1: ()Unit

  v.foreach2(f1)                                  //> f here
                                                  //| foreach2

  class MyClass[A] {

    def foreach2[B](f: Unit) = {
      println("foreach2")
      f
    }

  }

}

函数f1似乎在foreach2之前得到评估,因为“f here”在“foreach2”之前打印。为什么会这样?

1 个答案:

答案 0 :(得分:3)

由于您没有调用它,因此您将返回它,foreach2函数的推断结果类型将为Int => Int。您需要使用一些参数调用此函数。在第二种情况下应用特殊规则,您可以调用函数f1(不带参数)而不使用大括号,因此基本上您将f1调用的结果(没有大括号)绑定到f函数的foreach2参数。

相关问题