lapots
lapots

Reputation: 13395

custom type conversion from string to some object

I want to add conversion to class String for object with type Example.

When I do like this

class Example {
    def x = 5
}

class ExampleConversionCategory {
    static def support = String.&asType
    static Object asType(String self, Class cls) {
        if (cls == Example.class) {
            "convert"
        } else { support(cls) } // argument type mismatch
    }
}

String.mixin(ExampleConversionCategory)

def x = "5" as int
println x

I get exception

java.lang.IllegalArgumentException: argument type mismatch

What is the problem? cls has Class type.

Upvotes: 4

Views: 1484

Answers (1)

Renato
Renato

Reputation: 13690

You were pretty close...

Notice that the asType method is implemented by the Groovy's String extension class, called StringGroovyMethods.

So the code that works is this one:

import groovy.transform.Canonical
import org.codehaus.groovy.runtime.StringGroovyMethods

@Canonical
class Example {
    def x = 5
}

class ExampleConversionCategory {
    static final def convert = StringGroovyMethods.&asType

    static def asType( String self, Class cls ) {
        if ( cls == Example ) new Example( x: 10 )
        else convert( self, cls )
    }
}

String.mixin( ExampleConversionCategory )

println "5" as int
println 'A' as Example

Which prints:

5
Example(10)

Upvotes: 7

Related Questions