https://kotlinlang.org logo
#language-proposals
Title
# language-proposals
s

Sam Stone

08/02/2022, 7:48 AM
I would like to propose a feature: lambda as extension function. My use case: in Android, Timber records the class that requested a log event along with the log. I have a few wrappers of this that I put in my util class, for example.
fun <T> ld(t: T, getMessage: (T) -> String) = Timber.d(getMessage(t))
and
fun <T> T.ld() = this.also { Timber
.
d(it) }
The issue is that the class is always the util class. Writing
val
`ld = {(
insert previous code)
}` works for the former wrapper, but not the latter. I use the latery for chaining.
t

Trevor Stone

08/02/2022, 5:13 PM
Copy code
val <T> T.ld: T.() -> T
    get() = { this.also { println(it) } }
Does this work?
called like
Copy code
123.ld()
s

Sam Stone

08/05/2022, 3:13 AM
Why do you use a computed property instead of an extension function?
t

Trevor Stone

08/05/2022, 1:25 PM
For lack of a better answer "Because it seems to work and provide similar functionality to what I believe you were describing"
s

Sam Stone

08/05/2022, 4:05 PM
But that doesn’t replicate the behavior. What about
getMessage
?
And I have another version that takes an `R`:
Copy code
fun <T, R> T.ld(message: R) = this.apply { Timber.d(message.toString()) }
t

Trevor Stone

08/05/2022, 4:13 PM
I’ll be honest with you, I’m a bit lost now with what problem you’re trying to solve
s

Sam Stone

08/07/2022, 2:41 PM
The Timber logging library captures the class from which a logging function was called. I created a wrapper function for the long
Timber.d()
as
ld()
. Because
fun ld()
is desclared in my utils class, the class reported in the logs is always my utils class, which completely removes the usefulness of that function, and the logs are harder to read. I am trying to find a way to call this function in a way that it will capture the class it was called in. I think wrapping the function in a lambda, and calling the lambda in the calling class will capture that class in the log (haven’t tried yet). One of the wrappers takes the receiver of
T.ld()
and passes it to the lambda (e.g.
"a".ld { "the letter is: $it" }
).