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

138
Visualizações
Lambda val with generic type in Kotlin

Say I've got this Kotlin typealias:

typealias Checker<T> = (T) -> Unit

fun <T> checkNothing(input: T) = Unit
fun <T> checkSomething(input: T) = makeSomeAssertion(input)

fun <T> doSomethingWithAChecker(checker: Checker<t>) { /* ... */ }

Now I can call doSomethingWithAChecker(::checkNothing) or doSomethingWithAChecker(::checkSomething), which is fine, but I'd rather define val's with lambdas and the proper type alias so there's only ever one instance:

val checkNothing: Checker<T> = { Unit }
val checkSomething: Checker<T> = { makeSomeAssertion(it) }

But of course since they're instantiated they can't have that generic T, so I either have to define a type, or I can't pass them into doSomethingWithAChecker.

Is this possible without type casts?

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

0

The val declarations can be wrapped into a generic class which would supply the types of the checkers.

class Checkers<T> {
    val checkNothing: Checker<T> = { Unit }
    val checkSomething: Checker<T> = { makeSomeAssertion(it) }
}
over 4 years ago · Santiago Trujillo Relatório

0

you can use the Any type here to accept anything:

val checkNothing: Checker<Any> = { Unit }
checkNothing(123)
checkNothing("abc")
val checkSomething: Checker<Any> = { makeSomeAssertion(it) }
checkSomething(123)
checkSomething("abc")

Since your checkers here are consumers, it may be more correct to use <in Any> rather than just <Any>; more details on that can be read up on in the generics reference documentation

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