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.

class="lang-scala prettyprint-override">opt.fold[status](err)(x => ok(x)) opt.fold(err: status)(x => ok(x))

scala type-inference

Comments

Popular posts from this blog

java - How to set log4j.defaultInitOverride property to false in jboss server 6 -

c - GStreamer 1.0 1.4.5 RTSP Example Server sends 503 Service unavailable -

Using ajax with sonata admin list view pagination -