kotlinreflection

How do I get the KType of Nothing?


I am doing Reflection Stuff™ with Kotlin, and I am trying to fill generic arguments with Nothing. However, for this I need a KType of Nothing. typeOf<Nothing>() doesn't work because I cannot use 'Nothing' as reified type parameter, and I do not know of an other way to get a KType of Nothing directly.

Right now, I am using

typeOf<List<Nothing>>().arguments.first().type

which gets me a KType of Nothing, but seems like a workaround. Is there another way I am missing?


Solution

  • For Kotlin/JVM:

    By inspecting the byte code that typeOf<List<Nothing>>() is compiled into, we can see that it is basically creating a KType like this:

    Reflection.typeOf(
        List::class.java, 
        KTypeProjection.invariant(
            Reflection.nothingType(Reflection.typeOf(Void::class.java))
        )
    )
    

    We can see that it uses Reflection.nothingType to create the KType representing Nothing, so you can use that directly.

    import kotlin.jvm.internal.Reflection
    
    Reflection.nothingType(typeOf<Void>())
    

    This calls ReflectionFactory.nothingType, which basically returns the same type as the KType passed in, just with a bit set in its flags.

    public KType nothingType(KType type) {
        TypeReference typeRef = (TypeReference) type;
        return new TypeReference(
                type.getClassifier(), type.getArguments(), typeRef.getPlatformTypeUpperBound$kotlin_stdlib(),
                typeRef.getFlags$kotlin_stdlib() | TypeReference.IS_NOTHING_TYPE
        );
    }