简体   繁体   中英

Scala function evaluation

In below code :

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
    }

  }

}

Why is function f1 not invoked within function foreach2 ?

If I instead use

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
    }

  }

}

The function f1 appears to get evaluated before foreach2 , as "f here" is printed before "foreach2". Why is this the case ?

Because you are not invoking it, you are returning it as a result, the inferred result type of your foreach2 function would be Int => Int . You need to invoke this function with some argument. In the second case a special rules applies, you can invoke function like f1 (which doesn't take arguments) without braces, so basically you are binding a result of f1 invocation (without braces) to the f parameter of your foreach2 function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM