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?
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) }
}
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