NMO
NMO

Reputation: 766

Adding methods to a list in Scala

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.

Upvotes: 0

Views: 87

Answers (2)

dursun
dursun

Reputation: 1846

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

Upvotes: 1

gzm0
gzm0

Reputation: 14842

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

Upvotes: 0

Related Questions