Cilenco
Cilenco

Reputation: 7117

Require a possibly nullable generic to be not null

In Kotlin I'm able to write a function which takes a generic possibly nullable argument from a super class - let's call it Person - and returns the exact same type like this:

fun <V: Person?> identity(arg1: V): V = arg1

val p1: Person? = identity(null) // works fine
val p2: Person = identity(Person()) // works fine
val p3: Person = identity(null) // does not work

Is it also possible to write a function like the one above which takes a second argument of type V which must not be null? I think about something like this where arg2 can not be null:

fun <V: Person?> identity(arg1: V, args2: V): V

Not that both args should have the exact same type so <V: Person?, W: Person> would not work.

Upvotes: 0

Views: 94

Answers (1)

user2340612
user2340612

Reputation: 10704

If I understood what you want to achieve, you could change V's upper bound to something not nullable and explicitly marking it as nullable wherever needed, like this:

fun <V: Person> identity(nullable: V?, nonNullable: V): V? = TODO() // do something

val p1: Person? = identity(null, Person()) // works fine
val p2: Person? = identity(Person(), Person()) // works fine
val p3: Person? = identity(null, null) // does not compile as second argument is null

Note that however you'll need to decide whether to return a nullable or non-nullable result, while in your original example that was inferred depending on whether the actual V was nullable or not.

Upvotes: 2

Related Questions