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

Eric Ou

07/05/2022, 10:51 AM
I've mentioned this on the forum before, but it didn't seem to get any response, what about a syntactic sugar, which allows you to declare one method which can accept multiple types, which just gets desugared into multiple methods? For example:
Copy code
fun timesTwo(num: Double[(s: String)->s.toDouble(), (n: Number)->n.toDouble()]) = num * 2
Which can be separated into two methods by the compiler, and this would get rid of conversion methods, which would reduce redundancy? Though admittedly the syntax I designed for it is pretty bad, but I trust you guys can do better than I can :D.
k

kioba

07/05/2022, 10:59 AM
Hey Eric, I think the idea is great! There are many cases where this level of abstraction might be valuable. if I understand correctly your suggestion, Context Receivers might be able to help you with it in the future.
Copy code
fun interface DoubleConverter<A> {
    fun A.toDouble(): Double
}

context(DoubleConverter<A>)
fun <A> timesTwo(num: A) : Double = num.toDouble() * 2
usage:
Copy code
val context = DoubleConverter { it: String -> it.toDouble() }
with(context) {
  timesTwo("3.14")
}
e

Eric Ou

07/05/2022, 11:01 AM
Interesting! I never really looked into the context system as I probably should, but it would still be nice to not need anything on the call site for this conversion :D. Edit: Oh it doesn't have a page on the doc :(
k

kioba

07/05/2022, 11:05 AM
Yeah, that is a fair point! I know that the #arrow team was talking about automatic Context inlining if they find an implementation of
DoubleConverter<String>
in the codebase.
Copy code
@Given
object StringDoubleConverter : DoubleConverter<String> { 
fun String.toDouble(): Double = it.toDouble()
 }
Copy code
timesTwo("3.14") // this works automatically as the compiler finds the DoubleConverter<String> in the codebase
PS: I don't exactly know where this idea is currently in the implementation but I remember there were discussions on this topic. Might be worth to check in with them 🙂
r

raulraja

07/05/2022, 2:32 PM
🙏 1
🙏 1
n

Niko

07/08/2022, 6:29 AM
I have also hoped Kotlin had a metaprogramming construct, e.g. like the C++ templating system. I had thought it could use the `expect`/`actual` pair to avoid additional runtime contexts or overhead from generics. However, I think the context receiver approach could also benefit my libraries to avoid writing N copy-pasted implementations or subtypes for each type the library supports
5 Views