0

I'm pretty new to Scala and I want to add a function to a list. I have the following:

 var l2: List[() => Unit] = List() def foo() { println("In foo") } 

And now I want to add a method to the list.

() => println("x") :: l2 

It compiles but it doesn't work at runtime.

Next question: Why doesn't the following compile?

l2 = foo :: l2 

Thanks.

2
  • Does l2 = (foo) :: l2 compile? Commented Jun 6, 2013 at 21:52
  • You might want to add, why your code does not work at runtime and what the compiler error message is. Commented Jun 6, 2013 at 22:30

2 Answers 2

1

this is not a correct syntax

() => println("x") :: l2 

the correct one is

(() => println("x")) :: l2 

and why l2 = foo :: l2 does not compile is because the type of foo does not compliant with l2 to understand it deeply try following

foo.toString 

however followings will be compiled

var fn = {() => println("y")} l2 = fn :: l2 

or

foo _ :: l2 
Sign up to request clarification or add additional context in comments.

3 Comments

() => println("x") :: l2 is correct syntax, but interpreted as () => (println("x") :: l2)
yes you are right I just wanted to say it does not work the way that @NMO wanted.
Sorry, nitpicking again. foo.toString does not return the type of (or information about) foo, but calls foo and returns the result (The unit-value () in this case).
0

First of all, () => println("x") :: l2 is interpreted as () => (println("x") :: l2). That is a function that takes no arguments and returns a List[Any] (after type inference).

As @dursun states, you want to write:

(() => println("x")) :: l2 

Further, l2 = foo :: l2 does not compile because Scala wants you to state explicitly, if you use a function value rather than apply it (basically to protect the programmer from misuse). Use:

foo _ :: l2 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.