The following code does not compile:
var next: (A, A) = (null, n)
Error:
error: type mismatch;
found : Null(null)
required: A
var next: (A, A) = (null, n)
Also var next: (A, A) = ((null: A), n)
fails with the same error.
Somehow I think it should compile.
I'm currently using the following code which seems to work:
var next: (A, A) = (null.asInstanceOf[A], n)
Why doesn't it work? Bug or feature?
After reading didiers answer the problem is obvious. I missed that null
can only be assigned to AnyRef
types. For my problem I choose to make the tuple (n,n)
and have a boolean flag whether the first entry is valid. Depending on the application Option
might be a better solution.
In Scala, using null to represent nullable or missing values is an anti-pattern: use the type Option instead. The type Option ensures that you deal with both the presence and the absence of an element. Thanks to the Option type, you can make your system safer by avoiding nasty NullPointerException s at runtime.
Null is - together with scala. Nothing - at the bottom of the Scala type hierarchy. Null is the type of the null literal. It is a subtype of every type except those of value classes.
In Scala, tuples are defined using a series of classes named Tuple2, Tuple3 all the way through to Tuple22.
As a word of caution (and balance), the Twitter Effective Scala page recommends not overusing Option , and using the Null Object Pattern where it makes sense. As usual, use your own judgment, but try to eliminate all null values using one of these approaches.
Probably because your A parameter type is not guaranteed to be <: AnyRef. It should if you intend to pass null. If so, I would say feature
Edit. See Daniel's comment below, the solution is >: Null, See AgileSteel answer too.
I'm not sure what you are trying to archive by using null
s (except more NPE at runtime), but I can recommend you not to use null
in your Scala code. Scala has Option
type that can be used instead of null
. So in your case it would look like this:
var next: (Option[A], A) = (None, n)
I find this code much more clear and it's big advantage, is that tuple type tells other people (and compiler) that it's first element is not some A
, but it either Some[A]
or None
.
If you need to integrate with existing Java code that uses null
, that you can wrap objects that come from Java side in option as soon as possible. You can make it like this:
var next: (Option[A], A) = (Option(getAFromSomeMethodThatCanReturnNull()), n)
This answer probably does not answer your original question, but I hope it would be somehow helpful.
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