Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get Option value or throw an exception

Tags:

scala

Given an Option, what is the idiomatic way to get its value or throw an exception trying?

def foo() : String = {   val x : Option[String] = ...   x.getOrException() } 
like image 801
ripper234 Avatar asked Apr 28 '13 13:04

ripper234


People also ask

What does throw() do?

The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.

What does it mean to throw an error?

One mechanism to transfer control, or raise an exception, is known as a throw. The exception is said to be thrown. Execution is transferred to a "catch"." Follow this answer to receive notifications.

What is getOrElse in Scala?

As we know getOrElse method is the member function of Option class in scala. This method is used to return an optional value. This option can contain two objects first is Some and another one is None in scala. Some class represent some value and None is represent a not defined value.

How do you throw an error in Scala?

The throw keyword in Scala is used to explicitly throw an exception from a method or any block of code.In scala, throw keyword is used to throw exception explicitly and catch it. It can also be used to throw custom exceptions. Exception handling in java and scala are very similar.


1 Answers

A throw "statement" is really an expression in Scala, and it has type Nothing, which is a subtype of every other type. This means you can just use plain old getOrElse:

def myGet[A](oa: Option[A]) = oa.getOrElse(throw new RuntimeException("Can't.")) 

You really, really shouldn't be doing this, though.

like image 200
Travis Brown Avatar answered Sep 22 '22 02:09

Travis Brown