Reputation: 417
The following code generates the compilation error Option[serializable] does not conform to Try[String]
In all the places where the method can return, I am returning either a Try(String)
or Failure(Exception)
. Given that why does compiler think I am returning Option[Serializable]
?
def m1(arg1 : String, arg2 : String): Try[String] = {
for {
x1 <- getM1(arg1)
x2 <- getM2(arg2)
} yield {
val id : Either[Exception, String]= weirdFunction(x1, x2)
id match {
case Left(e) => Failure(Exception("")))
case Right(id) => Success(id)
}
} getOrElse(Failure(Exception("")))
}
Upvotes: 1
Views: 1310
Reputation: 16324
It's just an issue of parentheses:
def m1(arg1 : String, arg2 : String): Try[String] = {
for {
x1 <- getM1(arg1)
x2 <- getM2(arg2)
} yield {
val id : Either[Exception, String]= weirdFunction(x1, x2)
id match {
case Left(e) => Failure(Exception("")))
case Right(id) => Success(id)
}
} /* getOrElse used to be here */
}.getOrElse(Failure(Exception("")))
The compiler thought you were trying to call getOrElse
on the Try
returned in the yield
statement (how could it know otherwise?). Since there is a getOrElse
method on Try
as well as Option
, this is a particularly confusing error message. So, it thought you were trying to either return the id
in the Success
of the yield
statement or the Failure
afterwards. Their least common super type is Serializable
, and since it thought we were still wrapped in the for
comprehension, it deduced the return type to be Option[Serializable
.
Upvotes: 3