Let's say I have an interface HasId
and another HasResponsiblePerson
.
I am now interested in an instance that implements both.
i.e.
typealias AssignableEntity = HasId & HasResponsiblePerson
class Foo {
val entity: AssignableEntity
}
But this fails because
Intersection types are only supported for definitely non-nullable types: left part should be a type parameter with nullable bounds
I could, of course, just define a new interface
interface AssignableEntity: HasId, HasResponsiblePerson
but then I have to define new interfaces every time I come across a new combination of interfaces I am interested in, and we end up with a ton of mostly useless interfaces.
Is there a way to do what I want?
CodePudding user response:
Intersection and union types are not denotable in Kotlin at the moment: https://youtrack.jetbrains.com/issue/KT-13108
As the message tells you, a first step in this direction was taken for T & Any
to represent definitely non-nullable types, but it's not yet available for general intersections.
In the meantime, you can use a dedicated interface, pass multiple arguments, or return a compound class as @Ivo suggested.
CodePudding user response:
It's not really an answer to the question I guess, but alternatively you maybe just do
class Foo {
val idEntity: HasId
val responsibleEntity: HasResponsiblePerson
}
Keep them in separate variables. And assign them the same object. In your code refer to the one that's relevant. This also makes it more flexible and makes you able to actually use different objects for it. If you specifically don't want them to be different you could maybe throw an error in that case, but admittedly that's maybe not a clean solution.