Is it possible to create an infix function scoped ...
# announcements
e
Is it possible to create an infix function scoped to a specific class? Something like:
Copy code
// Foo is a library class and out of my control
class Foo

infix fun Foo.togetherWith(first: Any, second: Any) = ...

inline fun fooBuilder(builder: Foo.() -> Unit) {
  Foo().apply(builder)
}

fooBuilder {
  1 togetherWith 2
}
I know this specifically doesn't work, but is there any way to achieve this behavior?
n
I think to do this you'd need to inherit from Foo
Or if that's not possible
Create a class that delegates, automatically or manually
And add the infix function too
a
This was discussed in Kotlin 1.4 Event, as a proposal iirc.
n
What exactly?
a
They were trying to fix a syntax, taking the suggestions from people. But don't know if it'll be implemented any before 1.5
n
IMHO the most natural path to fix this is to make delegation less clumsy
a
There's a highly requested KEEP proposal, lemme check its link
n
Not obvious to me why delegation required an interface really
Requires
Delegation has some odd restrictions, there's probably reasons but it is pretty limiting in the end regardless
a
Not all class members be overriden, they're final by default unless you
open
them
Maybe ^

https://www.youtube.com/watch?v=0FF19HJDqMo?t=13m20s

I think this talk discussed about this
Yeah it is ^
b
You already can do this. Declare your
togetherWith
function in Foo, rather than creating an extension function
a
He explicitly said:
// Foo is a library class and out of my control
b
Ah see
n
@Animesh Sahu it's not overriding though it's just delegation
👀 1
b
Then create FooBuilder class that proxies your lamda changes to actual Foo
n
It's code you can always write by hand, for any class, whether it's open or closed
Not sure if your video link is related to what I said about delegation or the original issue but I'll check it out
a
I mean implementing a List through either LinkedList or ArrayList makes sense, but implementing a LinkedList with ArrayList looks meh... 😛
What's the usecase?
n
You can't do that though... You can only delegate to a subtype
a
I mean yeah, sorry for bad examples 😅
n
The use case is anytime you want to extend a class you don't control
Even more useful is if the delegation still allows you to implement any functions by hand and override the "default" implementation you get from the delegste
This "proxy" or "facade" is one of the original design patterns, already has language support in Kotlin, you better believe use cases are common :-)
a
It gives you ability to iirc
n
Go also offers a language feature to deal with this use case
a
override fun f(...) { super<Interface1>.f(...); super<If2>.f(...) }
n
Right, nice
a
I have no idea of golang tbh sorry 😅
n
So yeah, just leaves the interface limitation, as well as some limitations of var val
Go has embedding. It's basically implementation inheritance, except that it doesn't make the class a subtype