Why does val x: Int = _
not compile but var x: Int = _
does?
I'm getting error: unbound placeholder parameter
.
The difference between val and var is that val makes a variable immutable — like final in Java — and var makes a variable mutable. Because val fields can't vary, some people refer to them as values rather than variables.
On the other hand, the val keyword represents a value. It's an immutable reference, meaning that its value never changes. Once assigned it will always keep the same value. Scala's val is similar to a final variable in Java or constants in other languages.
Scala allows the use of underscores (denoted as '_') to be used as placeholders for one or more parameters. we can consider the underscore to something that needs to be filled in with a value. However, each parameter must appear only one time within the function literal.
case _ => does not check for the type, so it would match anything (similar to default in Java). case _ : ByteType matches only an instance of ByteType . It is the same like case x : ByteType , just without binding the casted matched object to a name x .
In this context, _
means "I will initialize this later, just fill in whatever the sensible default is in the meantime". Since you can't reassign a val
, this doesn't make sense.
For the same functionality--to get the sensible default--for a val
, you can use
val x: Int = null.asInstanceOf[Int]
You can't reassign a vals value, so you cannot use _ (init with a default value for prescribed type) with it. But you can reassign a vars value, so it's a logical to initialize it with some default value, like in Java
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With