Enforcing parameter types on dependent interfaces?

These interfaces are very simple:

public interface Thawed<F>
{
    F freeze();
}

public interface Frozen<T>
{
    T thaw();
}

      

It works, no problem.

But now, as it took me F

to Thawed

realize Frozen

and T

to Frozen

to implement Thawed

?

The closest I could get is:

public interface Thawed<F extends Frozen<? extends Thawed<F>>>

public interface Frozen<T extends Thawed<? extends Frozen<T>>>

      

But that sounds pretty recursive ... (also works with Thawed<?>

and Frozen<?>

)

+3


source to share


2 answers


The closest thing I could get

This is the correct answer; you can't do more than a system like Java.


Note that this allows

class Cat implements Thawed<Dog> { }
class HouseCat extends Cat { }
class Dog implements Frozen<HouseCat> { }

      



This can be prevented by using two general parameters:

public interface Thawed<F extends Frozen<T, F>, T extends Thawed<F, T>> { }

public interface Frozen<T extends Thawed<F, T>, F extends Frozen<T, F>> { }

      

However, I think this is too confusing to be useful.

It would also allow

class Cat implements Thawed<Dog, HouseCat> { }

class HouseCat extends Cat { }

class Dog implements Frozen<HouseCat, Dog> { }

      

+1


source


I think this should work:

public interface Thawed<F extends Frozen<?>> { ... }

public interface Frozen<T extends Thawed<?>> { ... }

      



I don't think you need anything deeper, because all you have to do is indicate what F

is kind Frozen

(and similarly for T

).

+3


source







All Articles