scala - How to fix type inference error in this example? -
scala - How to fix type inference error in this example? -
suppose writing:
sealed trait status object error1 extends status case class ok(x: int) extends status def foo(opt: option[int]): status = opt.fold(error1)(x => ok(x)) when seek in repl error:
scala> def foo(opt: option[int]): status = opt.fold(error1)(x => ok(x)) <console>:11: error: type mismatch; found : ok required: error1.type def foo(opt: option[int]): status = opt.fold(error1)(x => ok(x)) ^ i can work around not particularly elegant:
// work around type error above val error1: status = error1 def ok(x: int): status = ok(x) def foo(opt: option[int]): status = opt.fold(error1)(x => ok(x)) how suggest solving type problem ?
as see fold infers homecoming type zero/fallback value provided first arg. there error resolve specific type of value.
you can annotate fold in next ways indicate want status.
opt.fold[status](err)(x => ok(x)) opt.fold(err: status)(x => ok(x)) scala type-inference
Comments
Post a Comment