Traits in Groovy comes as a good replacement to Java's interfaces and, in particular Java 8's interfaces that features default methods. Though, while working on a project in Groovy, I've come across a counter-intuitive and (AFAIK) undocumented limitation of traits: inner traits and access to enclosing class' variables.

The case I'm describing may be exotic and have other ways to be solved that I'm not aware of. In an Android application, the framework instanciates an Application <https://developer.android.com/reference/android/app/Application.html> object. This class can be overriden to let the developer perform initialization steps before the application displays (like list files). This Application object is (in theory) unique for an Android application. In order to simplify the code, I tried to make some methods of this class accessible to any other class implementing an inner trait. Here is an example:

public class CustomApplicationextends 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?

Regards,
Henry Christophe

Reply via email to