javakotlinkotlin-java-interop

Kotlin loses nullability information when removing redudant SAM constructor from java


I'm using SendBird in one of my project. One of the function is used to connect to the sdk:

SendBird.connect(id, token, object : SendBird.ConnectHandler {
    override fun onConnected(user: User?, e: SendBirdException?) {
        if (e != null) {
            // handle error
        } else {
            // handle success
        }
    }
})

Kotlin hints me that I can convert this to a lambda:

SendBird.connect(userId.toString(), accessToken) { user, e ->
    if (e != null) {
        // handle error
    } else {
        // handle success
    }
}

The issue is that inside the lambda user is of type User! while the real type is User? which sometime leads to crash.

The SendBird android sdk is written in java and nothing is annotated properly with @Nullable/@NonNull. Any way to use the lambda while keeping the nullable type User??


Solution

  • specify the type explicitly

    SendBird.connect(userId.toString(), accessToken) { user: User?, e ->
        if (e != null) {
            // handle error
        } else {
            // handle success
        }
    }