Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Different behavior of val and var with an anonymous function and a placeholder

Code with val and var:

val adder: Int => Int = _ + 3 // Works fine
var adder: Int => Int = (_ + 3) // Works fine
var adder: Int => Int = _ + 3 // Error (using var, but not brackets)

Error message for the last line with var:

';' expected but identifier found.

What can explain the difference in behavior between the val and var variant?

like image 216
gaurav pandey Avatar asked Mar 15 '19 12:03

gaurav pandey


Video Answer


1 Answers

In Scala one of the many things underscores are used for is to allow users to set a default initial value in var definitions (see section 4.2 of the spec):

scala> var x: String = _
x: String = null

scala> var y: Int = _
y: Int = 0

The problem you're seeing seems to be that an underscore immediately following the = in a var definition is interpreted as this special default initial value, and the alternative use as a placeholder in a function is not considered.

This behavior seems to me like it must be a bug. I'm pretty sure it can't be justified by the spec, and it seems pretty reasonable to expect the compiler to consider both syntactic uses of _. At a glance I can't turn up an issue, though. If you care you might try reporting it yourself.

Since you don't actually ask a question, I'm just guess about what information is going to be helpful to you. You're probably not asking about workarounds, since you've got one right there in your second line, so it's likely you're just wondering what's up with this, in which case the answer is that the Scala compiler is still kind of a buggy mess in some ways, especially in less-used or cared-for areas of the language (like var definitions).

like image 109
Travis Brown Avatar answered Oct 10 '22 21:10

Travis Brown