Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

143
Views
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 answers
Answer question

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!