Search code examples
groovy

WHY the variable types of goovy class can be converted?


class TestClass{
    String a;
    ArrayList b;
}

TestClass test1 = new TestClass(a: 123) //the value passed in for variable a is Int type, why not print error?
println test1.a.getClass() //print 'class java.lang.String'.

TestClass test2 = new TestClass(b: 123) //the value passed in for variable b is also Int type, print GroovyCastException at this time: Cannot cast object '123' with class 'java.lang.Integer' to class 'java.util.ArrayList'
println test2.b.getClass() //no execution.

Why there's no error reported when passing Int values to variable a?

My expectation: when passing Int values to variable a, will report error, like variable b.


Solution

  • So tim_yates' article explains WHY this is happening. What can you do about it?

    Groovy can mix of dynamic typing and static typing. So parts of your app can be dynamically typed and others can be statically typed. You have access to those choices through a series of annotations. If you want something like Java then use the @CompileStatic annotation.

    @CompileStatic
    public class TestClass {
       String a
       List b
    }
    
    TestClass t1 = new TestClass( a: 123 )
    

    And you'll get an error you expect. You can also turn on type checking, but continue to use dynamic features of Groovy with the @TypeChecked annotation.

    @TypeChecked
    public class TestClass {
       String a
       List b
    }
    
    TestClass t2 = new TestClass( a: 123 )
    

    That will also generate an error. So what's the difference? @TypeChecked method dispatch continues to go through MOP (Meta Object Protocol) where @CompileStatic tries to align with javac compilation. Therefore, some MOP features are not available to @CompileStatic where they are in @TypeChecked. The performance of @CompileStatic is higher and very close to Java's performance where @TypeChecked will not be. But that is why you can mix and match these to take advantage of performance vs expressiveness depending on the problem at hand.