I'm trying to implement an Option which doesn't consume extra memory for a wrapper. I create a class. Null stands for None, non-null value stands for Some.
class Maybe[+T](private val nullable: T) extends AnyVal {
@inline final def isDefined: Boolean = {
println("isDefined called")
val res = nullable != null
println(s"result = $res")
res
}
@inline final def get: T = if (isDefined) nullable else throw new NoSuchElementException
@inline final def getOrElse[B >: T](default: => B): B = if (isDefined) this.get else default
@inline final def map[B](f: T => B) : Maybe[B] = if (isDefined) Maybe.some(f(this.get)) else Maybe.none
@inline final def flatMap[B](f: T => Maybe[B]): Maybe[B] = if (!isDefined) Maybe.none else f(get)
def toOption : Option[T] = if (isDefined) Some(get) else None
}
object Maybe {
def some[T](value:T) : Maybe[T] = new Maybe(value)
final val none : Maybe[Nothing] = {
println("start initializing none")
val v = new Maybe(null)
println("1")
val res = v.asInstanceOf[Maybe[Nothing]]
println("2")
res
}
}
object MaybeTest extends App {
println("try to create Maybe.none")
val myNone = Maybe.none
println("Initialized")
println(myNone.isDefined)
println("Accessed")
}
But when I try to run it I get an NPE:
try to create Maybe.none
start initializing none
1
2
Initialized
Exception in thread "main" java.lang.NullPointerException at com.MaybeTest$.delayedEndpoint$com$MaybeTest$1(Maybe.scala:34) at com.MaybeTest$delayedInit$body.apply(Maybe.scala:30) at scala.Function0$class.apply$mcV$sp(Function0.scala:34) at scala.runtime.AbstractFunction0.apply$mcV$sp(AbstractFunction0.scala:12) at scala.App$$anonfun$main$1.apply(App.scala:76) at scala.App$$anonfun$main$1.apply(App.scala:76) at scala.collection.immutable.List.foreach(List.scala:392) at scala.collection.generic.TraversableForwarder$class.foreach(TraversableForwarder.scala:35) at scala.App$class.main(App.scala:76) at com.MaybeTest$.main(Maybe.scala:30) at com.MaybeTest.main(Maybe.scala)
If I remove 'extends AnyVal' everything works fine. Could anyone explain such behavior?
null
... which is more of a runtime entity and can not be distinguished at compile time into your "supposedly null-free" ecosystem. And then you are even working hard to do it. Well Done. – sarveshseriMaybe[Int]
at runtime as anInt
. Scala's type system mandates thatNothing
is inhabited by zero values, not even null. Yet it will find a null at runtime to represent yourMaybe[Nothing]
. Strange things will happen. – Jasper-M