groovy-dev mailing list archives

Site index · List index
Message view « Date » · « Thread »
Top « Date » · « Thread »
From Jochen Theodorou <>
Subject Re: Inner traits?
Date Mon, 29 Feb 2016 10:29:46 GMT

On 27.02.2016 19:29, Christophe Henry wrote:
> public class CustomApplication extends Application
> {
>      private static instance @Override void onCreate()
>      {
>          super.onCreate()
>          instance =this }
>      public trait ApplicationUtilities
>      {
>          public ContextgetApplicationContext(){return instance.applicationContext }
>      }
> }
> While this piece of code would have worked with an abstract class or a
> Java 8's interface, it throws a compilation error with a trait.
> I know I'm trying to do unnatural things with this language but is there
> any reason for this limitation and is there a plan to implement a
> feature like this in future releases?

Hmmm, I wonder if this can be made sense of or not. A trait can be seen 
as some independent piece that can be added to a class. But for it to be 
independent, it cannot be non-static. In your code the trait 
implementation would depend on an instance of CustomApplication and 
cannot be created without supplying such an instance. If I now have a 
random class X, how can I let that use the trait without an instance of 
CustomApplication? I cannot. Then how does the instance get there? Is 
there one instance per trait usage, or do all traits share the same 
CustomApplication instance (as would be the case in the non-static case 
for inner classes!)d

So what makes no sense is to have a

class X implements CustomApplication.ApplicationUtilities {}

What could work is something like:

class X {
   def someField
   trait T {
     def getField() {return someField}
   class Y implements T {
   def foo(){ return new Y() }

def x = new X()
assert x.someField ==

I kind of doubt you wanted this later version... and does not anyway... 
yes, the inner class cases have been totally ignored so far. Even making 
the trait static is raising havoc in the compiler... and that at least 
should have passed compilation and only failed when trying to access 

Though... further thought leads me to see things a little different. In 
a trait you can do

trait X {
   def foo() { return bar }

class Y implements X{
   private bar = 1

The property bar is not existing in the trait, it is expected on 
"traited" class. Following this logic, what does it mean to access the 
field of an outer class? Strictly following this logic means not to be 
able to do that. Resolving first outer class fields and then traited 
class means to get into trouble with dynamic properties.

bye Jochen

View raw message