Generate when cases for KClass<SealedClass>

How to make compiler generate (and enforce exhaustiveness check) on the KClass instance of a sealed type just like it would on an actual instance of that sealed class

fun map(type: KClass<SomeSealedClass>) =
    when (type) {
           .... here I want compiler to generate exhaustive case branches ...
    }

Basically I need to run some configuration code for each subclass of a sealed class, but with compiler making sure I dont miss any.

2 Likes

You probably meant this instead: :wink:

KClass<out SomeSealedClass>

This cannot be made to work. An exhaustive set of classes is known by the compiler, but it cannot be guaranteed at run time.

Why does it need to be exhaustive? Can’t you do something like this?

when (type) {
    is SomeSealedClassSubClass -> ...
    else -> throw IllegalStateException("Unknown type: $type")
}

Why it cannot be gauranteed? How is it different from typechecking the actual SomeSealedClass?
I certainly can do something like this, but I want compiler to make sure I wont miss anything when I’ll add new SomeSealedClassNewSubClass. Also I want it to generate me the branches :slight_smile:

1 Like

There is a huge difference between SomeSealedClass and KClass<SomeSealedClass. They are not similar at all from the compiler’s point of view. For example, SomeSealedClass is an actual sealed class, while KClass<SomeSealedClass> definitely is not.

when can only determine whether its branches are exhaustive for sealed classes, so if you use it on KClass<...>, the compiler cannot help you.

Of course, the compiler can be extended to understand that KClass<SomeSealedClass> means that only the KClass of one of the subclasses of SomeSealedClass will be possible there. But for everything there is a cost: complexity, development time, etc. I am not sure if it will be worth the effort for this edge case.

What is it you are trying to do? Maybe there is another way.