https://kotlinlang.org logo
#getting-started
Title
# getting-started
j

Jonathan Locke

03/02/2023, 1:47 PM
hi there. is there a way to apply an interface to an existing object? for example, i might like to make an Addable interface and apply it to Collection, sort of like extension methods, except extension interfaces. thanks
a

August Lilleaas

03/02/2023, 1:54 PM
as in, make built-in interfaces/classes implement your own interfaces?
j

Jonathan Locke

03/02/2023, 2:27 PM
yes. something like Collection : Addable, where Addable is my interface.
where Addable is:
Copy code
interface Addable { 
    fun add(element: E): Boolean 
}
v

Vampire

03/02/2023, 3:15 PM
But how should an instance of
Collection
then implement that interface? Or do you only use that to redeclare methods that are already present? If the latter, then you probably wait for denotable union and intersection types I'd guess.
j

Jonathan Locke

03/02/2023, 7:02 PM
only what is already implemented. so List implements Collection.add(E) and I could pass a list instance to a method that takes Addable. is there a place I can read about union and intersection types?
if you mean that I could write a method like myMethod(container : Addable | Collection), it's not really the same thing because you would have to add an arbitrary number of types to the union. but maybe I'm misunderstanding?
that's also useful, of course, but what i'm asking about is more like
Copy code
interface kotlin.collections.Collection.Addable
(consistent with extension method syntax
v

Vampire

03/02/2023, 7:27 PM
I don't think it is possible, and I'd doubt it will ever be possible. Probably the closest is to have an extension method or extension property
toAddable
or
asAddable
or similar that gives you an
Addable
wrapper for that type.
j

Jonathan Locke

03/02/2023, 10:12 PM
I guess it could be too complicated
thanks
the extension method is a good idea as a substitute
👌 1
2 Views