Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

137
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda