https://kotlinlang.org logo
#getting-started
Title
# getting-started
l

Lukasz Kalnik

11/03/2023, 2:44 PM
Why does the type of the result of the
left()
function here must have
R?
, although
R
is already by definition nullable?
Copy code
class Either<L, R> private constructor(
    private val left: L,
    private val right: R,
) {

    companion object {

        fun <L, R> left(left: L): Either<L, R?> {
            return Either(left, null)
        }
    }
}
j

Joffrey

11/03/2023, 2:46 PM
What makes you say that
R
is by definition nullable?
R
is only nullable if the caller of this function specifies it as such. This signature forces
Either.left<Int, String>(42)
to return an
Either<Int, String?>
. Were it not for the so called "definitely nullable"
R?
, it would be expected to return
Either<Int, String>
which is not possible given the body of the function (so defining the function without
?
would not compile)
l

Lukasz Kalnik

11/03/2023, 2:47 PM
You're right, I was thinking, because
R : Any?
that it's guaranteed to be nullable. But indeed it depends on the concrete instantiation of the class. It can be nullable, but doesn't have to.
👌 1
Thanks!
j

Joffrey

11/03/2023, 2:48 PM
You're welcome 🙂