Cake pattern with Java8 possible?

前端 未结 5 1478
无人共我
无人共我 2020-12-24 06:32

I just wonder: with Java 8, and the possibility to add implementation in interfaces (a bit like Scala traits), will it be possible to implement the cake pattern, like we can

5条回答
  •  梦谈多话
    2020-12-24 06:49

    A few experiments suggest no:

    • Nested classes are automatically static. This is inherently uncakelike:

      interface Car {
          class Engine { }
      }
      
      // ...
          Car car = new Car() { };
          Car.Engine e = car.new Engine();
      
      error: qualified new of static class
          Car.Engine e = car.new Engine();
      
    • So, apparently, are nested interfaces, although it's harder to coax out the error messages:

      interface Car {
          interface Engine { }
      }
      
      // ...
          Car car = new Car() { };
          class Yo implements car.Engine {
          }
      
       error: package car does not exist
              class Yo implements car.Engine {
      
       // ...
      
      class Yo implements Car.Engine {
      }                                                                                                      
      
      
       // compiles ok.
      

    So, without instance member classes, you do not have path dependent types, which is basically necessary for the cake pattern. So at least, no, not in the straightforward way, it is not possible.

提交回复
热议问题