Ofir Bar

    Ofir Bar

    2 years ago
    May be stupid but a junior dev here 😄 Is there a particular good reason to have a generic function parameter type inherit from “Any”? In the image, the method we use, and the second one is without it.
    d

    Drew Hamilton

    2 years ago
    In the second one,
    T
    can be a nullable type. In the first one, it can’t be.
    wcaokaze

    wcaokaze

    2 years ago
    Yep. In other words,
    <T>
    means
    <T : Any?>
    Ofir Bar

    Ofir Bar

    2 years ago
    Hmm.. didn’t expect that. So by default, Kotlin generics allow nulls.. isn’t that goes against how Kotlin tries to fight NPE? I would expect
    <T>
    to behave such as
    <T: Any>
    and to have a null value explicitly use
    <T: Any?>
    @Drew Hamilton @wcaokaze
    d

    Drew Hamilton

    2 years ago
    I think either way you’d have to “just know” which one is the default because different people would have different intuitions. But IMO it makes sense because
    Any?
    is the lowest common denominator; the most generic available type in the JVM.
    arekolek

    arekolek

    2 years ago
    one example where
    T : Any
    makes sense:
    data class Optional<T : Any>(val value: T? = null)
    
    interface Test {
        fun test(): Optional<String?> // compilation error
    }
    It's a constraint https://kotlinlang.org/docs/tutorials/kotlin-for-py/generics.html#constraints so it makes sense that without no constraints it is the most general type
    Ofir Bar

    Ofir Bar

    2 years ago
    Got it, that makes sense thank you!