How to fix type inference error in this fold example?
As you see fold
infers return type from the zero/fallback value provided as first arg. There it is Error
as it resolve the most specific type of the value.
You can annotate the fold in the following ways to indicate you want a Status
.
opt.fold[Status](err)(x => Ok(x))
opt.fold(err: Status)(x => Ok(x))
The compiler infers that the type is Error1 because that is the type of the first parameter passed to fold.
In terms of the answer to the direct question, you can tell the compiler that it is an Error1, but that the relevant type is Status, by passing the type explicitly as Status
sealed trait Status
object Error1 extends Status
case class Ok(x: Int) extends Status
def foo(opt: Option[Int]): Status = opt.fold(Error1: Status)(x => Ok(x))
Function foo will then return as follows:
scala> foo(Option(5))
res0: Status = Ok(5)
fold signature looks like:
final def fold[B](ifEmpty: ⇒ B)(f: (A) ⇒ B): B
So, it is a curried function with a type parameter B
. So it first executes opt.fold(Error1)
and infers that B is Error1
. So, the second part (x => Ok(x))
should be (f: (A) => Error1)
, and for that reason the compiler complains.
You can fix it being explicit with the type as follows:
scala> def foo(opt: Option[Int]): Status = opt.fold[Status](Error1)(x => Ok(x))
foo: (opt: Option[Int])Status