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

Sam

08/04/2022, 7:54 AM
Suggestion: allow omitting the receiver type from a callable reference when it can be inferred from the expected type.
Copy code
data class A(val name: String)

fun <B> A.getProp(prop: A.() -> B) = prop(this)

fun A.getName() = getProp(::name) // I want this

fun A.getName2() = getProp(A::name) // But I have to do this instead
1
(From this thread)
r

Roukanken

08/04/2022, 8:42 AM
can it be inferred?
Copy code
data class A(val name: String)
fun A.name() = TODO()

fun <B> A.getProp(prop: A.() -> B) = prop(this)

fun A.getName() = getProp(::name) // which one am I referring to?
s

Sam

08/04/2022, 8:52 AM
👍 that’s a good example of a case where it would be ambiguous; I guess there are plenty more too. In that case I agree the receiver is definitely still needed. Omitting it would only be feasible in certain situations where it’s not ambiguous.
r

Roukanken

08/04/2022, 8:54 AM
well the problem is, if you allow receiver to get omitted, then afaik in my case you have no way to refer to the extension function (because compiler would have to tell you it's ambiguous, and it can't choose between property or the method)
therefore, to allow the omitting, you would also need to introduce some syntax that would express "this is definitely not on a class"
s

Sam

08/04/2022, 8:57 AM
Ah, I see the problem 🤦 thanks for the explanation
I can think of a few ideas to get around it but none of them are very good. What I really want is a way to make the code more concise when the receiver name is very long.
r

Roukanken

08/04/2022, 9:57 AM
I guess best idea to resolve this would be a syntax of "pls infer the receiver" eg, something like
getProp(_::name)
s

Sam

08/04/2022, 11:02 AM
Yeah, it sounds like it would have to be something explicit like that. Which means the syntax is never going to feel totally clean. The underscore is a nice idea since it’s consistent with the new feature for omitting generic type parameters. But if it needs special syntax, maybe it’s not worth it 😞
5 Views