Mike Cantrell

2>&1

Groovy & Dynamic Typing vs. Weak Typing

Posted by mcantrell on August 30, 2008

Silly test incomming:


class DataTypeConversionTests extends GroovyTestCase {
    void testInteger() {
        Integer i = 49
        String s = '1'
        assert s == i
    }
}

Stupid test huh? No way it would pass.. Think again. Try it yourself. Then go lookup the ASCII value of 1.

You see.. it passes because Groovy has no concept of a character literal. In Java, single quotes are normally reserved to represent characters. Groovy allows them to represent a String. See the problem? Groovy does it’s best to compensate by considering all single character Strings as char date types when trying to convert.

Why would you ever do something so silly? It’s not as silly as you might think. Groovy and Grails provide a lot of abstractions. It’s not always obvious what types of data you are dealing with. Dealing with JSON or XML builders for instance. Additionally, Grails hides data binding behind a transparent beanwrapper in Controllers so you don’t see your HTTP parameters getting auto-converted inf the binding process. You can see how you could get lazy here.

If you’ve read Programming Groovy by Venkat Subramaniam (great book and even better speaker), you might take note with chapter 4.3. Venkat asserts that Groovy is both a dynamic and strongly typed language (aka dynamic != weakly typed). You should see an error at runtime if you do some funny business. That is true 99% of the time but it’s clearly not applicable for the scenario mentioned here.

I’m not sure any of this is cool but I’m not sure what else you would do if you allow Strings with single quotes and you also want a character data type.

Leave a Reply

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <pre> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>