scala - 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. example not compile:
persons = personsopt.fold(nil){person => person}
is there simple way type safety not have {person => person}
?
edit: 2 things concretely understood:
- there nothing un-type-safe
getorelse
. instance not compile:personsopt.getorelse("")
nil
list()
, if type can't inferred compiler ask explicit. there can no type issues usingnil
i couldn't find link now, did (incorrectly) read getorelse
somehow less type safe using fold
option
.
there function identity
defined in predef
:
persons = personsopt.fold(list[person]())(identity)
i find lot less readable using getorelse
, , using not make code more type-safe using getorelse
. note passing nil
getorelse
make return 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 persons
list[person]
.
Comments
Post a Comment