Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between underscore initialization of var and val

Tags:

scala

Why does val x: Int = _ not compile but var x: Int = _ does?

I'm getting error: unbound placeholder parameter.

like image 533
Rado Buransky Avatar asked Mar 12 '14 21:03

Rado Buransky


People also ask

What is difference between Val and VAR in Scala?

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.

What does Val mean in Scala?

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.

What does _ means in Scala?

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.

What does case _ mean in Scala?

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 .


2 Answers

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]
like image 80
Rex Kerr Avatar answered Oct 16 '22 09:10

Rex Kerr


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

like image 37
4lex1v Avatar answered Oct 16 '22 08:10

4lex1v