https://kotlinlang.org logo
#announcements
Title
# announcements
d

Dalinar

12/03/2017, 3:16 AM
I have classes A, B:A and C:A and D:A is there a way to define a type that is B or C but not D or anything else ? using generics. I guess I'll probably just add a shared interface to B and C but I'm curious
a

adam-mcneilly

12/03/2017, 3:19 AM
I don't know, but it makes me think the shared interface to B/C is a good idea. Having a condition that only allows 2/3 subtypes is a code smell to me. I say smell because it feels wrong, but I'm not sure how to justify that as wrong because I don't know the full context.
d

Dalinar

12/03/2017, 3:27 AM
not really sure, using an interface is not quite perfect because I'd have to cast it when I want to access anything
a

adam-mcneilly

12/03/2017, 3:29 AM
Can you give a little more insight? Understand if you can't, but if you can at least name A/B/C/D maybe it'll make more sense.
d

Dalinar

12/03/2017, 3:39 AM
yeah i guess it is harder to explain, I dumbed it down. I can't really insert a new superclass below A above B and C because C is actually AZC , so i thought I remembered seeing something with generics where you can combine multiple conditions but I wasn't totally sure and couldn't figure out how to google for it. Anyhow I'm mostly just interested to know if there is a way to define a type that can accept one of 2 different types
👍 1
a

adam-mcneilly

12/03/2017, 3:44 AM
I think this is similar, but they have two classes. Not class & interface unless the example was oversimplified too far.
d

Dalinar

12/03/2017, 3:49 AM
yes 2 classes is what I'm looking for
s

stkent

12/03/2017, 5:26 AM
Ah, gotcha
p

Pavlo Liapota

12/03/2017, 9:19 AM
You can also write:
Copy code
fun foo(b: B) = foo(b as A)
fun foo(c: C) = foo(c as A)
private fun foo(a: A) { /*...*/ }
2 Views