1

I want to initialize a variable of type Int as null in Scala but I am not able to do so -

scala> val a: Int = null
<console>:11: error: an expression of type Null is ineligible for implicit conversion
   val a: Int = null

But I can initialize a variable of type String as null in Scala:

scala> val a: String = null
a: String = null

Anyone know the reason for it?

Note - I am using Scala 2.11.8

himanshuIIITian
  • 5,985
  • 6
  • 50
  • 70
  • 1
    Not an answer to the question but it would be more normal (and better) to declarent it as an `Option[Int]`, that way you make it clear that it may be a none, whereas nulls are always nasty suprises – Richard Tingle Mar 14 '17 at 08:24
  • That is fine @RichardTingle, I am using `Option[Int]` in place of `null`. But, then why Scala is allowing me to do it for `String` type? – himanshuIIITian Mar 14 '17 at 08:28
  • 1
    See http://stackoverflow.com/questions/39210830/why-in-scala-long-cannot-in-initialized-to-null-whear-as-integer-can – nmat Mar 14 '17 at 08:30
  • 1
    Probably because java allows it (where Optional was only just introduced). Java allows a null string (because a string is an object) but no null int; because int is a primitive. I expect the scala designers didn't want to bring in a nasty feature no one should use just for consistency – Richard Tingle Mar 14 '17 at 08:31

1 Answers1

6

Null is a subtype of all reference types; its only instance is the null reference. Since Null is not a subtype of value types, null is not a member of any such type. For instance, it is not possible to assign null to a variable of type scala.Int. In other hand String is subtype of AnyRef which allows assigning null as value. For hierarchy reference

FaigB
  • 2,271
  • 1
  • 13
  • 22