scala - More concise way to class match and access last of Option[List] -
i have function parameter takes object , if of correct type need access last element in option[list[int]]. have working solution seems clumsy. in case there not items in obj.listofthings need have i have value 0. there better way achieve this?
val = foo match { case obj: bar => obj.listofints match { case some(ints) => ints.last case _ => 0 } case _ => 0 } technically return option[int]. i'm still pretty new scala , learn better approaches sort of problems.
in case seems ende neu suggested right way go:
val = foo match { case obj: bar => obj.listofints.map(_.last /* throws exception when list empty*/).getorelse(0) case _ => 0 } but if you'll see have bug in code, in case that obj.listofints some(nil), because in case nosuchelementexception trying call last on empty list.
try code foo = bar(some(nil)) , see yourself.
when use option[list] think if want. after thinking scrap option , stay list because option serves no purpose. worked many developers misuse option[list] because of not understanding similarities between nil , none , 'none' case ends playing same role some(nil)
so end having this:
optionallist match { case none => // case some(list) => list match { case nil => // same thing case head::tail => // other stuff } } as can see none case , some(nil) case same.
to fix bug should do:
case class bar(listofints: option[list[int]]) val = foo match { case bar(some(list)) if list != nil => list.last case _ => 0 }
Comments
Post a Comment