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:

  1. there nothing un-type-safe getorelse. instance not compile: personsopt.getorelse("")
  2. nil list() , if type can't inferred compiler ask explicit. there can no type issues using nil

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

Popular posts from this blog

OpenCV OpenCL: Convert Mat to Bitmap in JNI Layer for Android -

android - org.xmlpull.v1.XmlPullParserException: expected: START_TAG {http://schemas.xmlsoap.org/soap/envelope/}Envelope -

python - How to remove the Xframe Options header in django? -