|
|
|
|
|
by cachemoney
5359 days ago
|
|
An alternative is an option type. In scala, you have the abstract type Option[T], which has implementations Some[T](value: T) and None[T]. Alternately, you have Either[A, B], with implementations Left[A](value: A), and Right[B](value: B). So you can define a function that takes an Either[Int, ErrorMessage], rather than an Int or null. Getting a None[Int] is better than null, because it won't throw NullPointerExceptions if you access it sensibly. Examples: def x2or0(i: Option[Int]): Int = i.getOrElse(0) * 2
def x2(i: Option[Int]): Option[Int] = i.map(_ * 2)
def x2danger(iOrPossiblyNull: Int) = i * 2
// throws NullPointerException on null input
|
|