hey guys So i hav a base class called Wearable and...
# getting-started
o
hey guys So i hav a base class called Wearable and this class has a member named "name" And i hav another class name ClothTunic and this class inherits the class Wearable plus has a member named "armor" And say for examples sake, a class named PowerRing which inherits the Wearable and has a member named "strenght" So all this wearables are managed by a WearableManager which has a function called getTotalArmor() : Int which returns the total armor from all these wearables tht a entity has. So my question was this: How do i know which Wearable has a "armor" variable or a "strength" variable? How do i do it in Kotlin?
s
how do I do it in Kotlin
the same way you’d do it in any language - group classes together based on the shape you expect them to have, i.e. the methods they expose
Wearable
sounds like a very base interface that doesn’t cover your armor use case if it doesn’t apply to all of your wearables
n
in java you would use instanceof in kotlin we can use the magic of
is
and
when
Copy code
when(wearable) {
    is Stength -> { }
    is Named -> { }
}
Strength and named could be interfaces with just hose variables
s
you could create a different interface for armor and match upon it to access their respective
getTotalArmor()
method
n
although assuming osmething has both maybe you should just use multiple
if
s
or you could have every wearable implement an
armor
val and have items that don’t provide armor just return 0
n
technically oyu could (but shouldn't) use reflection
s
you don’t need reflection to model this.
o
yeah but Wearable objects might hav both armor or strenght How do i know which wearable object has which one?
n
assuming its with classes oyu do not control
o
yes i control them
n
Copy code
if(wearable is Named)


interface Named {
    var name: String
}
have some specific wearable implement Named and override the name
o
ok
but what if the Wearable hav both "armor" and "strenght" ?
n
then later you can filter a list of wearables with
wearabbles.filter { it is Named }
what then ? things can implement more than one interface.. whats the problem ? you need to check them seperately
o
ok
thnx a lot