https://kotlinlang.org logo
Title
m

Mahdi Javaheri

11/04/2018, 2:13 PM
can i use extension functions in polymorphic world? as i tested they are being resolved statically (at compile time)
open class AquariumPlant(val color: String)
class GreenLeafyPlant(size: Int): AquariumPlant("Green")

fun AquariumPlant.print() = println("AquariumPlant")
fun GreenLeafyPlant.print() = println("GreenLeafyPlant")

fun staticExample() {
    val plant = GreenLeafyPlant(size = 50)
    plant.print() // this print's GreenLeafyPlant

    val aquariumPlant: AquariumPlant = plant
    aquariumPlant.print() // this print's AquariumPlant !! but in polymorphism should be GreenLeafyPlant
}
is there a way to bypass this and benefit from Polymorphism
p

pdvrieze

11/05/2018, 4:40 PM
Extension functions can only be resolved statically. There are 2 workarounds: Define an extension for the parent type that uses a when for the child types and forwards to the correct one; Or use the visitor pattern and have the extension call the visitor function with a visitor that implements the methods for different types (this will fail to compile for missing cases).
open class Parent {
  open fun <R> visit(visitor: ParentVisitor<R>): R =
    visitor.visitParent(this)
}

class Child1: Parent() {
  override fun <R> visit(visitor: ParentVisitor<R>):R =
    visitor.visitChild1(this)
}

interface ParentVisitor<R> {
  fun visitParent(parent: Parent): R
  fun visitChild1(child1: Child1): R
}
👍 1