Ehm - but that is something that _should_ fail in my book, since it violates the contract of what a ctor does (namely create an object of his type). I am not saying Groovy should go out of its way to _prevent_ code like this - but if I had to choose between _this_ working and the imho helpful (and to me obvious) feature that final defined objects automatically carry their actual type instead of all being Object|s... well... you get my drift... Or do you see any application of doing something like this in a real word scenario, e.g. in the context of a DSL ?
Markus

On 24.08.2017 14:07, Paul King wrote:
It might be something that could work with @CompileStatic. For dynamic Groovy, I am not sure this can be done. Consider the following example which, although is dubious style, is valid Groovy:

Date.metaClass.constructor = { 42 }
final result = new Date()
assert result instanceof Integer
assert result == 42

Cheers, Paul.

On Wed, Aug 23, 2017 at 8:45 AM, MG <mg...@arscreat.com <mailto:mg...@arscreat.com>> wrote:

    Hi Paul,

    On 21.08.2017 04:30, Paul King wrote:
    Deduce the type of final fields from their assigned value:

        class Foo {
        final device = new PrinterDevice(...) // device field will
        have type PrinterDevice instead of Object when reflection is
        used on class Foo
        }
        Rationale: While IntelliJ does a good job at deducing the
        type of final fields, it would still be better if the Groovy
        language itself would use the more specialized type here, for
        e.g. reflection purposes

    With @Typechecked or @CompileStatic type inferencing is going to
    be in play. During debugging the runtime type is going to be
    available. What "reflective purposes" did you have in mind?

    In my framework I iterate over the fields of classes, which are of
    type Object, if the have been defined in a compact way using just
    final, without an explicit type - it would be helpful to have the
    type here.
    And in general it just feels like a lost opportunity that final
    fields/variables do not auto get the type of their assigned value
    - having more information available is never bad.
    Of course I am talking about this naively from a user's
    perspective: Do you think adding this would a) be hard / time
    intensive (naively I would have thought no), b) break backwards
    comptability (since the final variable/field cannot be
    reassigned... (?))...

    Cheers,
    Markus





Reply via email to