I have an Option, say O, which can either be None or may have some value inside. If it has some value, that value may have a flag, say f. My requirement is that if O is None, then I create an object, say of type MyEntity,but if O has a value with flag as true, I return Nil else I create instance of MyEntity with different value. Java code can be almost as:
if(O.isEmpty) {
MyEntity("x")
} else {
if(O.f) {
Nil
} else {
MyEntity("y") // with different value
}
}
I want to do this in functional style using HoFs provided in scala.Option. What would be best possible way of doing it? I could this so far :
if(O.isEmpty){
MyEntity("x")
} else {
Option.unless(O.exists(_.f))(MyEntity("y"))
}
Anysince that si the upper bound betweenMyEntityandNilare you sure you want that? Also, it may help if you provide the definition of the value inside the Option - In any case, I would write this using pattern matching rather than higher order functions.Nilis a name of an empty list. The proper Scala code would be returningOption[MyEntity]and the implementation would be something likeO.filterNot(_.f).map(_ => MyEntity("y"))MyEntityis different for the empty case and the non-empty but no-flag case.