Reputation: 35
how can I initialise and AnyVal value? If I initialise like this it shows 'Block cannot contain declarations'
var value: AnyVal
If I initialize like this it shows 'Required: Anyval, Found: Null'
var value: AnyVal = null
Can someone help me please? Thank you.
EDIT
I tried using the Option[AnyVal] and it works perfectly. Thank you for the help.
Upvotes: 0
Views: 171
Reputation: 1734
You can initialise it using _
, like:
var value: AnyVal = _
BTW, it is better to use some Wrapper type, that expresses the absence of the value. In Scala it is possible using Option
like:
var value: Option[AnyVal] = None
Upvotes: 1
Reputation: 76
First of all, I highly suggest using val
over var
and secondly why do you want to initialise to a default value and change it later? Almost many use cases can be achieved using immutability in Scala (which is good). If you could share your use case/example which is insisting you to use mutability, would be happy to take a look at it.
And it is always better to refrain from using null
and use Option
to represent absence, it avoids NullPointerException
s
Upvotes: 0