Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Option[A] in a function

I need a function which does something like the code below

def function[A,B](a: Option[A], f: Function[A,B]) = {
        a match {
          case None => None
          case Some(v) => Some(f(v))
        }
      }

Is there any scala built-in function which does the same?

like image 540
stsatlantis Avatar asked Apr 15 '26 22:04

stsatlantis


1 Answers

def function[A,B](a: Option[A], f: Function[A,B]) = {
  a.map(f(_))
}

Option can be treated as a Monad so many operations such as map, flatMap, and filter are available on it.

http://www.scala-lang.org/api/current/index.html#scala.Option

like image 125
mattinbits Avatar answered Apr 17 '26 12:04

mattinbits