hi there. is there a way to apply an interface to ...
# getting-started
j
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
as in, make built-in interfaces/classes implement your own interfaces?
j
yes. something like Collection : Addable, where Addable is my interface.
where Addable is:
Copy code
interface Addable { 
    fun add(element: E): Boolean 
}
v
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
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
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
I guess it could be too complicated
thanks
the extension method is a good idea as a substitute
👌 1