2

Here is java version:

Optional<Object> optionalFramework = Optional.empty();

optionalFramework.orElseThrow(IllegalStateException::new);

How to rewrite this in scala? (Note with using java.util.Optional not scala Option) How replace IllegalStateException::new in scala?

Cherry
  • 31,309
  • 66
  • 224
  • 364

1 Answers1

2

If you're using Scala 2.12.x, you can use a SAM type:

val a = Optional.of(10)
a.orElseThrow(() => new IllegalStateException("Can't do that"))

Otherwise, you'll need to implement the full Supplier interface:

a.orElseThrow(new Supplier[Throwable] {
  override def get(): Throwable = new IllegalStateException("Nope")
})

There's no exact equivalent syntax for Method Reference in Scala, it is similar to the syntax of a lambda expression, but not quite.

Yuval Itzchakov
  • 146,575
  • 32
  • 257
  • 321