scala: How to handle Option in a functional way -
i new scala question stupid. if have existing method below. adding these 4 lines method. there better way handle option value?
def processdata(input: string, datamap: map[string, string]): option[string] = { //4 lines adding. val data: option[string] = datamap.get(input) if (data.isempty) { return none } //how avoid line val datavalue = data.get //20-25 lines of code in here bunch of pattern matching case statements cleandata(datavalue) dosomethingelse("apple", datavalue, "test") }
essentially want avoid having "data.get" in below code. somehow feels wrong call that. wrote differently using pattern matching below. 20-25 lines of code have bunch of case statements , dont want create layer on top of them.
def processdata(input: string, datamap: map[string, string]): option[string] = { datamap.get(input) match { case some(datavalue) => { //20-25 lines of code in here bunch of pattern matching case statements cleandata(datavalue) dosomethingelse("apple", datavalue, "test") } case none => none }
}
any ideas?
actually second way of functional style, conciseness can use 1 of option
higher order functions:
def processdata(input: string, datamap: map[string, string]): option[string] = datamap.get(input).map { datavalue => cleandata(datavalue) dosomethingelse("apple", datavalue, "test") }
you can avoid dots , parentheses :
def processdata(input: string, datamap: map[string, string]): option[string] = datamap input map { datavalue => cleandata(datavalue) dosomethingelse("apple", datavalue, "test") }
Comments
Post a Comment