Syntactic sugar and Java arrays.

Recently I got surprised by following case.

In Java you can declare an array in following valid ways:

String[] strings = new String[] { "foo", "bar" };
// the above is equivalent to the following:
String[] strings = { "foo", "bar" };

So following Java code is perfectly valid:

public class Foo {

    public void doSomething(String[] arg) {}

    public void example() {
        String[] strings = { "foo", "bar" };
        doSomething(strings);
    }

}

Is there any valid reason why, instead, the following code shouldn't be valid?


public class Foo {

    public void doSomething(String[] arg) {}

    public void example() {
        doSomething({ "foo", "bar" });
    }

}

I think, that the above syntax would have been a valid substitute to the varargs introduced in Java 5. And, more coherent with the previously allowed array declarations.


Un Commento a “Syntactic sugar and Java arrays.”  

  1. 1 jan

    sure it is not valid…try the following:
    doSomething(new String[] {”foo”,”bar”});

    why should he know it’s a string array in the first place? ok it’s defined by the method doSomething…but how should he know, that what you are giving in is really such a type :)

Lascia un Commento

XHTML: Puoi utilizzare questi tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>



Calendario

Gennaio 2010
L M M G V S D
« Dic    
 123
45678910
11121314151617
18192021222324
25262728293031

Categorie