Unhelpful warning "Conditional branch result is implicitly cast to kotlin.Any"


#1

After switching to 1.0.0-rc-1017, we now get quite a few of these warnings, none of which seems to be helpful/warranted.

Here is an illustration:

interface Foo {
  // methods are called for their side effects, 
  // return "this" to allow builder-style chaining (third-party API)
  fun foo(): Foo
  fun bar(): Foo
  fun baz(): Foo
}

fun main(foo: Foo, condition: Boolean) {
  with(foo) {
    if (condition) {
      foo()
      bar()
      baz() // result type Foo, intentionally neglected
    } else {
      doSomethingWithFoo(this) // result type Unit, intentional
    }
  }
}

private fun doSomethingWithFoo(foo: Foo) {}

Same when using other side-effecting methods that return values, e.g. File.delete().

I understand what the warning is trying to achieve, but isn’t this too aggressive in the face of such “statement” use?


#2

For a last expression in lambda we can’t really tell the difference between a result of lambda (which is ignored later) and a result of expression that is coerced to Unit and ignored. Current behavior is somewhat counter-intuitive: it is a lambda that actually returns Foo (or kotlin.Unit) as a value of type Any. Then the result of ‘with’ is dropped.
So yes, you are right, the warning is not quite helpful, but the problem is a bit deeper.
I suppose the semantics should be changed together with the removal of this warning.


#3

https://youtrack.jetbrains.com/issue/KT-10919