Chris Murphy
Chris Murphy

Reputation: 6509

Using fold on Option without having x => x

Given:

val personsOpt:Option[List[Person]] = ???

I prefer:

persons = personsOpt.fold(List[Person]()){person => person}

To this:

persons = personsOpt.getOrElse(List[Person]())

For type safety reasons. For example this does not compile:

persons = personsOpt.fold(Nil){person => person}

Is there a simple way to get the type safety but not have {person => person}?

EDIT: Two things now concretely understood:

  1. There is nothing un-type-safe about getOrElse. For instance this does not compile: personsOpt.getOrElse("")
  2. Nil is List() and if its type can't be inferred the compiler will ask you to be explicit. So there can be no type issues with using Nil

I couldn't find the link just now, but I did (incorrectly) read that getOrElse was somehow less type safe than using fold with an Option.

Upvotes: 1

Views: 80

Answers (1)

Jesper
Jesper

Reputation: 206776

There is the function identity which is defined in Predef:

persons = personsOpt.fold(List[Person]())(identity)

I find this however a lot less readable than using getOrElse, and using this does not make your code more type-safe than using getOrElse. Note that passing Nil to getOrElse will make it return the correct type:

scala> case class Person(name: String)

scala> val personsOpt:Option[List[Person]] = None
personsOpt: Option[List[Person]] = None

scala> val persons = personsOpt.getOrElse(Nil)
persons: List[Person] = List()

Note that persons is a List[Person].

Upvotes: 5

Related Questions