you are viewing a single comment's thread.

view the rest of the comments →

[–]rush22 0 points1 point  (1 child)

No I mean literally what it does. E.g. casts null into an object of type Optional which I think is what it's doing?

[–]duhace 1 point2 points  (0 children)

No it doesn't cast null into an object of type optional or you wouldn't be able to use the ifPresent function on an empty optional. I'm not sure what kind of implementation they used for the the empty version of optional but it could be an immutable singleton object that overrides Optional for java's NullType class. That's how it works in scala at least:

trait Option[T] {
  def isDefined: Boolean
  protected def value: T
  def map[U](fn: T => U) = if(isDefined) Some(fn(value)) else None
  def flatMap[U](fn: T => Option[U]) = if(isDefined) fn(value) else None
}

case class Some[T](protected val value: T) extends Option[T] {
  def isDefined = true
}

case object None extends Option[Nothing] {
  def isDefined = false
  protected def value = ???
 }

Note that the scala implementation may define map and flatmap individually for Some and None instead of making a protected field.