scalascala-2.9

What is the difference between different function creations


This question is heavily related to my other question (and may lead to me solving that one) but is definetely different.

how to allow passing in a => AnyRef function and call that function

I have been playing with different function creations and I am frankly having trouble creating an anonymous function of type => AnyRef and => String. I can create a function of type () => AnyRef and () => String I think.

Example 1 I have the following code

def debugLazyTest2(msg: => String) : Unit = {
  System.out.println(msg)
}

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

but the compile error says found: () => String which makes sense but then says "required: String" instead of "required: => String"

What is going on here?

Example 2 to get even more bizarre, I have this code which compiles while above did not compile

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)

This code compiles though it doesn't work the way I would like as the library can't seem to invoke the function before toString is called (that is in my other thread and is a separate question).

Any ideas as to what is going on here?

thanks, Dean


Solution

  • If you wrote this it would work:

    log2.debugLazyTest2(function())
    

    msg is a by-name parameter, not a function. You have to pass in an expression of type String (or AnyRef in the second example)

    The second example compiles because the () => AnyRef you pass in is actually also an AnyRef, since a function is an AnyRef. But then it is the function itself that is printed, not the result of executing it.