Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

288
Visualizações
Reified inline function in Kotlin still leading to compiler error on 'is' check

I have the following function:

inline fun <reified T> create(preference: Preference<T>, title: String = ""): DebugOption{
        val type = when (preference) {
            is Preference<String> -> Type.STRING
            is Preference<Boolean> -> Type.BOOLEAN
            else -> Type.STRING
        }

        return DebugOption(type, preference, displayTitle = StringModel(title))
    }

I was expecting to be able to easily perform this 'is' check, since the generic type is reified, but I am still getting a compiler error:

Cannot check for instance of erased type: Preference<String>
Cannot check for instance of erased type: Preference<Boolean>

So I am confused how am I misusing 'reified' / what am I missing here. Is there a problem with using reified generic types as the type parameter of another class?

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

The problem is that is checks the runtime type of preference, and the runtime type of preference isn't available until all the generic type information has been erased. Reified types are not magic, after all.

What you can do instead, is check T instead, since as you said, T is indeed reified.

val type = when (T::class) {
    String::class -> Type.STRING
    Boolean::class -> Type.BOOLEAN
    else -> Type.STRING
}

But note that if Preference is covariant (like List) or contravariant, this might not work as you expect in some cases. For example:

// suppose Preference is covariant 
// (i.e. the type parameter is declared <out T>)
val pref: Preference<Any> = Preference<Boolean>()
create(pref, "foo")

In this case, T is inferred to be Any, so type will be assigned Type.STRING. If that is unexpected to you, and you want Type.BOOLEAN instead, you might want to use another way to check a preference's type, rather than reified types, as this cannot be determined at compile time.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda