Rob
02/22/2019, 5:15 PMabstract class A()
class B(): A()
class C(): A()
fun foo(b: B)
fun foo(c: C)
If I have something like this, a base class with subclasses and overloaded functions, what is the "best" way to call it IF they are stored in a variable of type A?
class Something(val member: A)
val v = Something(B())
foo(v.member) // How to get this to call the right foo
Dico
02/22/2019, 5:17 PMDico
02/22/2019, 5:17 PMif (a is B) {
foo(a)
}
natpryce
02/22/2019, 5:18 PMfoo
an abstract method in A, with implementations in B
and C
natpryce
02/22/2019, 5:18 PMfoo(a)
call the method, if you don’t want the change to impact existing client codeRob
02/22/2019, 5:18 PMRob
02/22/2019, 5:19 PMnatpryce
02/22/2019, 5:19 PMnatpryce
02/22/2019, 5:19 PMnatpryce
02/22/2019, 5:20 PMwhen
expression to switch on the subtype of A. That way the compiler tells you if foo
no longer handles all subclasses of A if you add a new oneDico
02/22/2019, 5:20 PMfoo
is a top level functionRob
02/22/2019, 5:21 PMwhen (v) {
is B -> foo(v)
is C -> foo(v)
is D -> foo(v)
}
is there no better way?Dico
02/22/2019, 5:21 PMfoo
are top level functions nonatpryce
02/22/2019, 5:21 PMDico
02/22/2019, 5:21 PMDico
02/22/2019, 5:22 PMnatpryce
02/22/2019, 5:22 PMnatpryce
02/22/2019, 5:23 PMRob
02/22/2019, 5:23 PMDico
02/22/2019, 5:23 PMnatpryce
02/22/2019, 5:24 PMDico
02/22/2019, 5:24 PMDico
02/22/2019, 5:25 PMDico
02/22/2019, 5:25 PMDico
02/22/2019, 5:25 PMnatpryce
02/22/2019, 5:26 PMnatpryce
02/22/2019, 5:27 PMDico
02/22/2019, 5:28 PMDico
02/22/2019, 5:29 PMnatpryce
02/22/2019, 5:30 PMDico
02/22/2019, 5:30 PM