NLinker icon

Kotlin typing is unsound

NLinker | PRO | 05/05/25 08:48:10 AM UTC | 0 ⭐ | 14265 👁️ | Never ⏰ | []
Kotlin |

700 B

|

Software

|

0 👍

/

0 👎

open class Animal
 
class Cat() : Animal() {
    fun myaw() {
        System.out.println("myaw!");
    }
}
 
class Dog() : Animal() {
    fun gav() {
        System.out.println("dog!");
    }
}
 
// Usage:
//     val list = mutableListOf<Int>()
//     list.addAnything("string")
//     val fail = list[0]
private fun <E> List <E>.addAnything(element: E) {
    if (this is MutableList<E>) {
        this.add(element)
    }
}
 
fun main() {
    val cats = mutableListOf<Cat>(Cat(), Cat())
    val upcast: List<Cat> = cats
    val covariance: List<Animal> = upcast
    val animals: MutableList<Animal> = covariance as MutableList
    animals[0] = Dog()
    for (cat in cats) {
        cat.myaw()
    }
}

Comments

  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎

    
        
  •  icon
    01/01/70 12:00:00 AM UTC
    Plain Text |

    0 B

    |

    👍

    /

    👎