Let’s say I have a MyObject instance which is not initialized:
var a:MyObject = null
is this the proper way to initialize it to null?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Alternatives
Use
nullas a last resort. As already mentioned,Optionreplaces most usages of null. If you usingnullto implement deferred initialisation of a field with some expensive calculation, you should use alazy val.Canonical initialisation to null
That said, Scala does support
null. I personally use it in combination with Spring Dependency Injection.Your code is perfectly valid. However, I suggest that you use
var t: T = _to initializetto it’s default value. IfTis a primitive, you get the default specific to the type. Otherwise you getnull.Not only is this more concise, but it is necessary when you don’t know in advance what
Twill be:Advanced
Using
var t: T= nullis a compile error if T is unbounded:You can add an implicit parameter as evidence that
Tis nullable — a subtype ofAnyRefnot a subtype ofNotNullThis isn’t fully baked, even in Scala 2.8, so just consider it a curiousity for now.