Erik Colban
04/04/2019, 6:03 PMbbaldino
04/04/2019, 6:11 PMbbaldino
04/04/2019, 6:14 PMTimeIt
to look like?Erik Colban
04/04/2019, 6:32 PM::myFun.timeIt()(arg1, arg2, ...)
bbaldino
04/04/2019, 6:34 PM_myFun
or something) and then have myFun
invoke _myFun
via the extension?Erik Colban
04/04/2019, 7:04 PMtimeIt
, the function provider would just provide the function any form she prefers, as a fun or a lambda. The caller would add the decorator as an extension function. For decorators such as memoize, the function provider would have to write the function to be decorated in a special form, which is what I don't like with my approach. This is discussed in detail in the README.Mike
04/04/2019, 11:13 PMbbaldino
04/04/2019, 11:35 PMErik Colban
04/05/2019, 6:49 PMmeasureTimeMillis
is different from timeIt
1. timeIt
prints the time, measureTimeMillis
doesn't print anything
2. measureTimeMillis
is a function that takes a code block as argument, whereas timeIt
is a decorator, i.e. it takes an object or class of some type T
and augments or modifies the behavior in some way and returns an object or class of the same type T
.Erik Colban
04/05/2019, 6:55 PMmeasureTimeMillis
and timeIt
have their usages, and comparing them is not the issue of this post. timeIt
is just an example of a function decorator. Decorators are well-known and even have their own pattern; the decorator pattern. Kotlin's by delegate
makes this pattern even easier to adopt. The point I wanted to address is how do you write a decorator on a recursive function in Kotlin that is applied recursively.bbaldino
04/05/2019, 6:58 PMErik Colban
04/05/2019, 7:00 PMinvoke()
) there is no value in doing so.bbaldino
04/05/2019, 7:01 PMby
like properties, right? are you talking about doing something like class Foo {
fun something() = delegate {
}
}
?Erik Colban
04/05/2019, 7:05 PMclass TimeIt<X, Y>(delegate: (X)->Y): (X)->Y by delegate {
override fun invoke(x: X): Y {
val start = System.currentTimeMillis()
val result = delegate.invoke(x)
println( System.currentTimeMillis() - start)
return result
}
}
bbaldino
04/05/2019, 7:06 PMErik Colban
04/05/2019, 7:11 PMTimeIt(::myFun)(x)
or, if you were to use a lambda,
TimeIt({....})(x)
Using an extension function is an alternative, and it's a matter of taste which to prefer.bbaldino
04/05/2019, 7:56 PM