Understanding Option Method

135 views Asked by At

For the following map signature, am I reading it correctly?

   object OptionImpl extends Option {
        def map[B](f: A => B): Option[B]
    }

source - FP in Scala

[B] means only objects of type B can call this function

f: A => B means that it accepts 1 argument, a function, that returns the same type B

I'm fuzzy on a concrete example of this function.

2

There are 2 answers

4
Rex Kerr On BEST ANSWER

B is just a wildcard (i.e. generic). It just says that these two types are the same:

def map[B](f: A => B): Option[B]
                   ^          ^

That is, it says: if you pass me a function that converts As to Bs, I will give you back an Option that may contain a B (where B can be any type).

0
Vishal John On

This is a very useful link http://blog.tmorris.net/posts/scalaoption-cheat-sheet/ on usage of Option.

If you have scenario like this

 option match {
   case None => None
   case Some(x) => Some(foo(x))
 }

use

option.map(foo(_))

Another example

def processBody(contentType: String): String = {
 .....
}

val body: Option[String] = 
   headers.get("Content-Type").map(processBody(_))

I assumed here that headers.get returns an Option.