coding style - Can I get Scala to infer the Option type here? -
i want call generic function f[x](...)
, , in case x
happens option[y]
. try pass both some[...]
, none
function expects x
, scala insists x
of type some[y]
.
def flattenoptionmap[a, b](input : map[a, option[b]]) : option[map[a, b]] = { input.foldleft[option[map[a,b]]] (some(map.empty)) { case (_, (_, none)) => none case (none, (_, _)) => none case (some(acc), (key, some(value))) => some(acc + (key -> value)) } }
in example, had explicitly specify option[map[a,b]]
should used generic type foldleft
. necessary type information contained in context, , typing cumbersome types option[map[a,b]]
more necessary in opinion drastically reduces readability of code.
is there way scala infer type after all, or otherwise avoid copy-pasting whole type?
when use option(map.empty[a, b])
start value of foldleft
, scala infer correct type wrote in comments (and beefyhalo in answer).
i add, if open using scalaz, can use sequence
function.
import scalaz._ import scalaz._ val mapsome = map(1 -> some("a"), 2 -> some("b")) val mapnone = map(1 -> some("a"), 2 -> some("b"), 3 -> none) mapsome.sequence flattenoptionmap(mapsome) // option[map[int,string]] = some(map(1 -> a, 2 -> b)) mapnone.sequence flattenoptionmap(mapnone) // option[map[int,string]] = none
Comments
Post a Comment