Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is there an Option.get method

Why is the method get defined in Option and not in Some?

One could apply pattern matching or use foreach, map, flatMap, getOrElse which is preferred anyway without the danger of runtime exceptions if None.get is called.

Are there really cases where the get method is so much convinent that it justifies this? Using the get method reminds me to Java where "I don't have to check for null because I know the var is set" and then see a NullPointerException.

like image 593
Manuel Schmidt Avatar asked May 21 '13 04:05

Manuel Schmidt


2 Answers

Option.get is occasionally useful when you know, by reasoning that isn't captured by the type system, that the value you have is not None. However, you should reach for it only when you've tried:

  • Arranging for this knowledge to be expressed by your types.
  • Using the Option processing methods mentioned (flatMap, getOrElse etc), and none of them fit elegantly.

It's also convenient for throwaway / interactive code (REPL, worksheets etc).

like image 158
Matt R Avatar answered Oct 27 '22 20:10

Matt R


Foreword

Scala was created with compatibility for the JVM as a target.

So it's pretty natural that Exceptions and try/catch should be considered as part of the language, at least for java interoperability.

With this premise in mind, now to the point of including interfaces that can throw errors in algebraic data types (or case classes if you prefer).


To the Question

Assume we encapsulate the get method (or head for List) only in Some instance.
This implies that we're forced to pattern match on the Option every time we want to extract the value. It wouldn't look pretty neat, but it's still a possibility.

We could getOrElse everywhere but this means that I can't signal a failure through the error stack if using imperative style (which is not forbidden in scala, the last time I checked).

My point here is that getOrElse and headOption are available to enforce a functional style when desired, but get and head are good alternatives if imperative is a choice fit to the problem or the programmer's preference.

like image 44
pagoda_5b Avatar answered Oct 27 '22 20:10

pagoda_5b