Wigi the Pug
Wigi the Pug

Reputation: 1

Why doesn't the underscore work here?

New to scala and wondering why the underscore doesn't work on the last line below, whereas the 'for' loop syntax at line 3 works fine. BTW Leaf is a case class and can accept (Char, Int) to apply/construct. Thanks!

  val chars: (List[Char]) = List('a', 'b')
  var leaves: ListBuffer[Leaf] = ListBuffer()

  for (c <- chars) leaves.append(Leaf(c, 1))//ok
  leaves.foreach(leaves.append(Leaf(_, 1)))//COMPILE ERROR

Upvotes: 0

Views: 65

Answers (1)

sepp2k
sepp2k

Reputation: 370425

The rules of _ notation are such that Leaf(_, 1) is equivalent to x => Leaf(x, 1), so leaves.foreach(leaves.append(Leaf(_, 1))) is equivalent to leaves.foreach(leaves.append(x => Leaf(x, 1))). This is an error because leaves.append doesn't take a function and also because foreach does.

What you want is leaves.foreach(x => leaves.append(Leaf(x, 1))), which gives foreach a function. However I'd expect that this still would not work as x would have type Leaf and I'd expect that you can't wrap a leaf around another leaf.

Upvotes: 3

Related Questions