Abdulelah Al Jeffery Abdulelah Al Jeffery - 1 year ago 67
Scala Question

Scala: multiplying Some type by Int

At Devoxx conference this year, Dick Wall gave a presentation on designs and patterns in Scala programming; and the first part was supposed to be brief highlights on the basics. At 1:09:35, he wrote the following function:

def safeDiv(a: Int, b: Int): Option[Int] = if (b == 0) None else Some(a / b)

which returns an compile error [good]. My question is since this is a fairly common scenario to encounter: how can I do integer operations * / + - on the returned value of

safeDiv(6, 2) // Some(2)

something like

safeDiv(6, 2) * 6 // 18 [error]

Answer Source

You cannot multiply Option on Int, you definitely should multiply value of Option like so:

 saveDiv(6, 2).map (_ * 6)  // Returns Option[Int]

or you can use "Pimp My Library" pattern to define method '*' on Option of Int:

 class PimpedOption(oi:Option[Int]) { 
   def *(i:Int) = oi.map(_*i)

 implicit def instance(oi:Option[Int]) = new PimpedOption(oi)

Then you can do:

 saveDiv(6, 2) * 6 // Gives Option[Int]