Could it be a bug in type inference? Works fine wi...
# announcements
g
Could it be a bug in type inference? Works fine without
if
but fails otherwise. Type mismatch error:
Copy code
sealed class Foo

object Valid : Foo()
object Empty : Foo()

fun doSomething1(): Result<Foo> {
    return Result.failure<Valid>(Exception()).recover { if (true) Empty else Valid }
}
Works fine:
Copy code
fun doSomething2(): Result<Foo> {
    return Result.failure<Valid>(Exception()).recover { Empty }
}
youtrack 1
s
Because you tell
Result.failure
that you will return
Valid
, but then you return
Empty
. This should work (failure<Valid> replaced with failure<Foo>)
Copy code
fun doSomething1(): Result<Foo> {
      return Result.failure<Foo>(Exception())
         .recover { if (true) Empty else Valid }
   }
Oh, I see what you mean, why does doSomething2 know how to handle this properly? Not sure actually.. 😅 Somehow it knows to convert to
Result<Foo>
/shrug
g
yeah, seems to be a bug, because it also works, if you assign the if expression to a variable. It just fails to do it on the fly.
m
Empty is likely an object of Result<Nothing> and so returning a Result<Nothing> is ok for Result<Foo>. If you return a Valid, then it's a Result<Valid> rather than a Result<Foo> and Result<Valid> doesn't work. I don't think it's strictly a failing. I also suspect you could do
return Result.failure(Exception())...
and the compiler would infer the return type correctly.
s
I still think there’s a failure here. There’s no reason this should fail
Copy code
fun doSomething1(): Result<Foo> {
   return Result.failure<Valid>(Exception())
      .recover {
         val temp = if (true) Empty else Valid
         return@recover temp
      }
}
If this works (just removed return@recover)
Copy code
fun doSomething1(): Result<Foo> {
   return Result.failure<Valid>(Exception())
      .recover {
         val temp = if (true) Empty else Valid
         temp
      }
}
💯 1
g
Filled in an issue on youtrack. Btw, seems to be fixed in the new type inference, enabled by
-XXLanguage:+NewInference
. https://youtrack.jetbrains.com/issue/KT-35514
👍 1