Andrew Gazelka
07/12/2019, 6:25 PMfun <T> wrapperFunc(block: (…) -> T): (…) -> T{
println("wrapped")
return block (…) -> T
}
and call it like
val testFunc = wrapperFunc {
fun(a: String) -> println("a is $a")
}
testFunc("abc")
Luke
07/12/2019, 6:31 PMtestFunc("abc")
?Andrew Gazelka
07/12/2019, 6:31 PMtestFunc("abc")
would print to sout
wrapped
abc
streetsofboston
07/12/2019, 6:35 PM...
, like a vararg kind a thing, but each argument should be individually typed (and on top of that, i think that lambdas can take a vararg).Al Warren
07/12/2019, 6:36 PMinternal var clickListener: (T) -> Unit = { }
Then the concreted class does this:
setOnClickListener { clickListener(data) }
Finally, the calling class does this:
adapter.clickListener = ::onItemClick
Luke
07/12/2019, 6:38 PMAl Warren
07/12/2019, 6:39 PMbloder
07/12/2019, 6:42 PMstreetsofboston
07/12/2019, 6:56 PMinfix fun <R> (() -> Unit).andThen(function: () -> R) : () -> R = {
this()
function()
}
infix fun <T1, R> (() -> Unit).andThen(function: (T1) -> R) : (T1) -> R = {
this()
function(it)
}
infix fun <T1, T2, R> (() -> Unit).andThen(function: (T1, T2) -> R) : (T1, T2) -> R = { t1, t2 ->
this()
function(t1, t2)
}
infix fun <T1, T2, T3, R> (() -> Unit).andThen(function: (T1, T2, T3) -> R) : (T1, T2, T3) -> R = { t1, t2, t3 ->
this()
function(t1, t2, t3)
}
fun prefix() {
println("wrapped")
}
fun functionToWrap(name: String, age: Int): String = "$name has age $age"
fun main() {
val testFunc = ::prefix andThen ::functionToWrap
println(testFunc("Jim", 45))
}
But, yes, for the vararg
like functionality, you’d need to define more and more andThen
functions, each one an extra Tn
generic parameter.