Don't understand why method param can be null here



I defined my own little extension function List.findIfNone:

fun <E> List<E>.findIfNone(searchBlock: (E) -> Boolean, ifNoneElement: E): E {
    val element = find { searchBlock(it) }
    if(element != null) {
        return element
    return ifNoneElement

Now I call it this way supplying null to the 2nd method parameter:

fun main(args: Array<String>) {
    val list = listOf("abc", "def", "ghi", "jkl", "mno")
    val foundElement = list.findIfNone({it == "ghi"}, null)

I don’t understand why I can put in null there although

ifNoneElement: E

is defined and not

ifNoneElement: E?

Am using Kotlin 1.3.11.


If no upper bound is specified for a generic parameter, it defaults to Any?, so you can use any type instead of E either nullable or not. If you wan’t to limit E to non-nullable types only, define its upper bound as Any:

fun <E : Any> List<E>.findIfNone(...)

I see, thanks. Think I need to start learning Kotlin a little more thoroughly …