0x56794E
0x56794E

Reputation: 21291

Why would/should this even be allowed?

I know not all WTFs are created equal but why would this even be valid. It does compile and only complains when you run it because it doesn't have static void main method, but other than that, it's syntactically correct. I tried giving it the main method, put it in a file named _.java and it did run.

class _<_>
{
    <_> _ _(_ _){ return (_)_; }
}

So obviously the "thing" inside class is a method which takes an argument whose name is the same as its type and returns whatever it got as argument. The (_)_ is obviously some casting. But I don't get the part before the (_ _). I guess the method's name is _, but what is <_> _? If it's generics, then shouldn't it be _<_>?

Upvotes: 1

Views: 44

Answers (2)

Erwin Bolwidt
Erwin Bolwidt

Reputation: 31279

The approach taken by @ravindrab is the right one, but the result is not correct.

  1. The declaration of the method type parameter <T> (<_>) in the original source code) shadows the declaration of the class type Node (_); so the argument is of type T, not of type Node
  2. The method type parameter also shadows the class's type parameter, so to avoid confusion it's better to give it a different name, like X.

Result:

class Node<X> {
    <T> T foo(T t) {
        return (T) t;
    }
}

The rules for shadowing are explained in JLS section 6.4.1. The specific one that applies to this case is:

A declaration d of a type named n shadows the declarations of any other types named n that are in scope at the point where d occurs throughout the scope of d.

Upvotes: 1

ravindrab
ravindrab

Reputation: 2782

Replace _ with something use full as suggested. Then you may see that <_> _ _(_ _) part is <T> Node foo(Node node). So it is the method name and the return type really.

class Node<T> {

    <T> Node foo(Node node) {
        return (Node) node;
    }

    public static void main(String[] args) {
        Node<String> a = new Node();
        Node<String> b = new Node();
        a.foo(b);
    }
}

Upvotes: 2

Related Questions