Ray Rahke
05/08/2024, 6:00 AMinterface Trait1 {
foo() { printn(5) }
}
interface Trait2 {
bar() { printn(7) }
}
class X : Trait1, Trait2
var x = X()
x.foo() // works!
x.bar() // works!
// later...
x = x.remove(Trait1)
x.foo() // alert! does not exist on type!
x.bar() // works still!
x = x.add(Trait1)
x.foo() // works again!Joffrey
05/08/2024, 9:04 AMval x = X() infers the type of x to X, so it implements both Trait1 and Trait2 (+ X-specific things).
If you declare another variable with an explicit static type you can reduce this:
val x = X()
val y: Trait1 = x
The variable y still points to the same instance of X as the x variable, but accesses through y can only use Trait1 operations.Joffrey
05/08/2024, 9:06 AMy from somewhere, and you somehow know that it must really be an X inside, you could cast it back to X to get the properties again:
val x2 = y as X // fails at runtime if y was not an instance of X
val x3 = y as? X // yields null if y was not an instance of XJoffrey
05/08/2024, 9:08 AMX() that you created initially doesn't change in any way. The only thing that changes is the static type of the reference variables that point to that instance of X. The compiler only cares about this for static analysis.Ray Rahke
05/09/2024, 1:27 PMRay Rahke
05/09/2024, 1:28 PMJoffrey
05/09/2024, 1:55 PM