Home > Back-end >  Kotlin how to enforce child class from parent class
Kotlin how to enforce child class from parent class

Time:09-28

This feels super trivial but my google and stack overflow result are filled with completely unrelated stuff.

In java, if an method call returns a parent class object, i.e.

ParentClass instance = someCall();

You can enforce this to be a child class and call child class specific methods by

(ChildClass) instance.doChildClassThings()

How does the same work in kotlin?

CodePudding user response:

You can use the as keyword to achieve the same functionality as

(ChildClass) instance.doChildClassThings()

instance.doChildClassThings() as ChildClass

or if instance is the ChildClass you are looking for

(instance as ChildClass).doChildClassThings()

https://kotlinlang.org/docs/typecasts.html

  • Related