Groovy: Is there a way to implement multiple inheritance when using type checking?

@groovy.transform.TypeChecked
abstract class Entity {
    ...
    double getMass() {
        ...
    }
    ...
}

@groovy.transform.TypeChecked
abstract class Location {
    ...
    Entity[] getContent() {
        ...
    }
    ...
}

@groovy.transform.TypeChecked
abstract class Container {...}  //inherits, somehow, from both Location and Entity

@groovy.transform.TypeChecked
class Main {
    void main() {
        double x
        Container c = new Chest() //Chest extends Container
        Entity e = c
        x = e.mass
        Location l = c
        x = l.content  //Programmer error, should throw compile-time error
    }
}

Essentially, is there a way to achieve this without sacrificing any of the three property loops in main():

  • Direct access to fields, even virtual fields
  • Purpose for both superclasses
  • Typechecking (at compile time)
+4
source share
1 answer

, . , ( : Groovy 2.3 !) , , @Mixin, .

: @Delegate - , , , Chest Container. .

, Groovy as, .

, abstract :

import groovy.transform.TypeChecked as TC

interface HasMass { double mass }
interface HasContent { Entity[] getContent() }

@TC class Entity implements HasMass { double mass }

@TC class Location {
    Entity[] getContent() {
        [new Entity(mass: 10.0), new Entity(mass: 20.0)] as Entity[]
    }
}

. HasContent Location, as.

-, Container Chest. @Delegate :

@TC 
abstract class Container {
  @Delegate Location location = new Location()
  @Delegate Entity entity = new Entity()
}


@TC class Chest extends Container { }

, , :

@TC class Mult {
    static main(args) {
        def x // use 'def' for flow-typing
        Container c = new Chest() //Chest extends Container
        HasMass e = c
        x = e.mass
        def l = c as HasContent

        x = l.content  //Programmer error, should throw compile-time error

        assert c.content.collect { Entity it -> it.mass } == [10.0, 20.0]
    }
}
+6

Source: https://habr.com/ru/post/1524430/


All Articles