How to do it in Scala:
sealed trait Option[+A] { def get: A def isEmpty: Boolean def map[B](f: A => B): Option[B] = if (isEmpty) None else Some(f(this.get)) } object None extends Option[Nothing] { def isEmpty = true def get = throw new NoSuchElementException("None.get") } case class Some[+A](x: A) extends Option[A] { def isEmpty = false def get = x }
As I guess it is in the OOP world:
sealed trait Option[+A] { def map[B](f: A => B): Option[B] } object None extends Option[Nothing] { def map[B](f: Nothing => B): Option[B] = this } case class Some[+A](get: A) extends Option[A] { def map[B](f: A => B): Option[B] = Some(f(get)) }
What happened to the last one?
Functional programming in Scala uses matchin the Option[A]tag what is the third way (looks like Haskell, but why?) Why not use the subtype polytype?
match
Option[A]
UPDATE . The third way:
sealed trait Option[+A] { def map[B](f: A => B): Option[B] = this match { case None => None case Some(a) => Some(f(a)) } } object None extends Option[Nothing] { } case class Some[+A](get: A) extends Option[A] { }
, , isEmpty get, , Option, Some. , map , , map , , map .
isEmpty
get
Option
Some
map
, , scala , java-, , .java-
val opt: Option[String] = ??? if (!opt.isEmpty) { //do something with opt.get } else { //do some default... }
, ( getOrElse).
@Victor Moroz this match { None => default_val; Some(v) => v }, , , , , , instanceOf , , .
this match { None => default_val; Some(v) => v }