Curious
Curious

Reputation: 921

Generics code coudln't understand why T parameter to be used

I'm looking over the code in generics. I'm tyring to understand the code but couldn't make sense about the usage of parameterized usage of T. Why T has to be used at all why not make it to work with E and R. As far as I understand E refers element and R refers to Tree. Coudn't make up the usage of generics in the code. Please someone expalin the code.

abstract class Tree<E> {
    public interface Visitor<E, R> {
        public R leaf(E elt);

        public R branch(R left, R right);
    }

    public abstract <R> R visit(Visitor<E, R> v);

    public static <T> Tree<T> leaf(final T e) {
        return new Tree<T>() {
            public <R> R visit(Visitor<T, R> v) {
                return v.leaf(e);
            }
        };
    }

    public static <T> Tree<T> branch(final Tree<T> l, final Tree<T> r) {
        return new Tree<T>() {
            public <R> R visit(Visitor<T, R> v) {
                return v.branch(l.visit(v), r.visit(v));
            }
        };
    }
}

Upvotes: 0

Views: 129

Answers (3)

PaulMurrayCbr
PaulMurrayCbr

Reputation: 1260

The types returned by the branch method have got nothing to do with the types of any other particular instance of Tree.

having said that, I'd have been inclined to use E. As far as I can see, the only restriction this would have placed on you is if you were invoking the static method as an instance method (which you are niot really supposed to do).

And yeah, the style is academic. Not pulling the final arguments into a named local does not really buy you anything except puzzlement. It's cute, that's all. People that like LISP like it because its a barrier to entry.

Upvotes: 0

Joop Eggen
Joop Eggen

Reputation: 109547

R stand for Result, of a visitor.

As @alphazero said T is for static usage:

Tree<String> helloLeaf = Tree.leaf("Hello");

The style is academic, a bit reminiscent of C++ STL, maybe a tidbit overengineered.

Upvotes: 2

Kleenestar
Kleenestar

Reputation: 799

The generic type <E> in this class is not visible for Class's static method or fields. So you are able to replace the <T> with <E>, it's only a name, but actually this <E> in the static method is different from the Tree<E>. You can try to change the signature as below to get the compile time error message.

public static Tree<E> leaf(final E e)

To remove the ambiguity, it's much better to use a different generic type name in the static method.

Upvotes: 3

Related Questions