4

Looking at some scala 2.10.4 library code:

implicit def wrapIntArray(xs: Array[Int]): WrappedArray[Int] = if (xs ne null) new WrappedArray.ofInt(xs) else null

What are the issues in making it:

if (xs != null) new WrappedArray.ofInt(xs) else null
Dragonborn
  • 1,755
  • 1
  • 16
  • 37
  • 1
    I don't think there is a difference in this case, but I am hesitant to use null in Scala - is there no way to rather use an Option? See http://stackoverflow.com/questions/10066927/what-is-the-difference-between-a-nenull-and-a-null-in-scala – Ewald Dec 03 '15 at 11:45
  • one more thing != is `not equals` while `ne` means `not ref` – HPKG Jun 24 '20 at 06:14

2 Answers2

3

Ideally this should be written to avoid nulls altogether, e.g.

implicit def wrapIntArray(xs: Array[Int]): Option[WrappedArray[Int]] = 
  Option(xs).map(a => new WrappedArray.ofInt(xs))

However given that this is a library function, changing its signature might not be possible. We could still use the Option approach internally though:

implicit def wrapIntArray(xs: Array[Int]): WrappedArray[Int] = 
  Option(xs).map(a => new WrappedArray.ofInt(xs)).getOrElse(null)
mattinbits
  • 10,370
  • 1
  • 26
  • 35
2

Consider writing this as:

implicit def wrapIntArray(xs: Array[Int]): Option[WrappedArray[Int]] = Option(xs).map(new WrappedArray.ofInt)

and work within the Option "context" (Option(xs) will be None if xs is null) rather than dealing with null.

Shadowlands
  • 14,994
  • 4
  • 45
  • 43