Example 8.1.2-1 Of Java Language Specification(Mutually Recursive Type Variable Bounds)

StackOverflow https://stackoverflow.com/questions/23248103

  •  08-07-2023
  •  | 
  •  

Question

I was reading jls 8 and I got stuck on Example 8.1.2-1, Mutually Recursive Type Variable Bounds I searched stackoverflow, and found a question what is a mutually recursive type? but this was not in terms of Java.

Example 8.1.2-1. Mutually Recursive Type Variable Bounds

interface ConvertibleTo<T> {
    T convert();
}
class ReprChange<T extends ConvertibleTo<S>,
                 S extends ConvertibleTo<T>> { 
    T t; 
    void set(S s) { t = s.convert();    } 
    S get()       { return t.convert(); } 
}

Question:

  • What does Recursive Type and Mutually Recursive Type means in Java?

  • Here what does T extends ConvertibleTo<S>, S extends ConvertibleTo<T> means?

  • If I just use T extends ConvertibleTo<S> as type parameter for class ReprChange I am getting compile time error?

Was it helpful?

Solution

What does Recursive Type and Mutually Recursive Type means in Java?

A recursive type is a type that uses itself in its definition. The simplest example is the linked list:

class List<T> {
    T value;
    List<T> next;
}

Here, List<T> is recursively defined because it uses a List<T> in its own definition.

A type variable bound (Foo in <T> extends Foo) is recursive if it references itself, e.g.

class Bar<T extends Comparable<T>>

would mean that class Bar expects a parameter T that can be compared to a T, so T references itself in its own definition.

Mutual recursion between two things means that they reference each other in their definition. In this case, the definition of S uses T and the definition of T uses S, so their definition is mutually recursive.

Here what does T extends ConvertibleTo<S>, S extends ConvertibleTo<T> means?

S and T are two types, S extends interface ConvertibleTo with T as the value of its type parameter, T extends interface ConvertibleTo with S as the value of its parameter. This implies that S has a method T convert() and T has a method S convert(). In other words, you can convert any S to a T and any T to an S.

If I just use T extends ConvertibleTo<S> as type parameter for class ReprChange I am getting compile time error?

Yes, because your definition mentions a type parameter named S that is never defined.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top