1

I was reading the definition of getOrElse in Option object:

def getOrElse[B >: A](default: => B): B

Why putting the arrow and not just writing?:

def getOrElse[B >: A](default: B): B

First I thougth that it was like saying "it receives a function that maps Unit to B" but I created a REPL session and it looks it doesn't means that.

scala> def f1(x: => Int) = x
f1: (x: => Int)Int

scala> f1(1)
res6: Int = 1

scala> def f1(x: Int) = x
f1: (x: Int)Int

scala> f1(1)
res8: Int = 1

scala> def f1(x: Unit => Int) = x
f1: (x: Unit => Int)Unit => Int

scala> f1(1)
<console>:10: error: type mismatch;
 found   : Int(1)
 required: Unit => Int
              f1(1)
                 ^
rsan
  • 1,887
  • 2
  • 17
  • 23
  • See also [Call by name vs call by value in Scala, clarification needed](http://stackoverflow.com/questions/13337338/call-by-name-vs-call-by-value-in-scala-clarification-needed) – senia Jul 04 '13 at 06:49
  • @senia thanks, new day, new lesson learned. I guess is desirable sending the default param this way in order to avoid computing the default if the Option is defined. If it is not defined then it will be substituted. Rigth? – rsan Jul 04 '13 at 07:02
  • @rsan yes, you're right – om-nom-nom Jul 04 '13 at 07:04
  • @om-nom-nom thanks, pal. Sorry for opening a duplicated question. – rsan Jul 04 '13 at 07:08
  • @rsan: I guess this example makes things clear: `myOption.getOrElse(sys.error("Exception thrown only if needed."))`. – senia Jul 04 '13 at 07:12

0 Answers0