1. Groovy has been a hybrid dynamic & static language for a long time:
   
https://docs.groovy-lang.org/latest/html/documentation/core-semantics.html#_static_compilation

    1. The @CompileStatic and @TypeChecked annotations can be applied
       to whole projects, classes or methods to switch the behavior of
       the Groovy compiler.
        1. (e.g. the vast majority of classes in our large Groovy
           project are annotated with either @CompileStatic or
           @TypeChecked)
2. However type inference also makes sense in dynamic Groovy, since of
   course not every variable has to have type Object:
    1. Consider the Groovy code var x = new StringBuilder() with type
       inference:
        1. StringBuilder x = new StringBuilder() // x would have type
           StringBuilder if Groovy var would use type inference
           (ignoring that Groovy new can be overridden to return a
           different type on purpose - type inference needs to be least
           surprise to be useful)
        2. x = "abc"  // Trying to reassign an incompatible type here
           throws
           org.codehaus.groovy.runtime.typehandling.GroovyCastException:
           Cannot cast object 'abc' with class 'java.lang.String' to
           class 'java.lang.StringBuilder'
    2. In Current Groovy with var = def = Object (for variables) this
       would of course work:
        1. Object x = new StringBuilder() // without type inference
           using var x here just always uses type Object
        2. x = "abc" // ok, an Object variable can hold any type

Cheers,
mg


On 22/11/2024 09:58, Gianluca Sartori wrote:

    var was always intended for the case of "type inference from an
    assignment", the way it is used in Java, and imho that is also
    what people coming fom other languages would expect.


My perception is that a feature like `var` is useful only when you cut-and-paste a Java code in a Groovy file, what is the use case that needs type inference in a dynamic language?

Reply via email to