Type type parameters in a nested generic type

I wrote this interface as part of the framework.

public interface CollectionFactory { public <T> Collection<T> newCollection(); } 

But I want the developer to be able to determine the return type of the collection, so they should not be selected as:

 public interface CollectionFactory<C extends Collection> { public C newCollection(); } 

The problem is that I then lose types on T. I would like her to be

 public interface CollectionFactory<C extends Collection> { public <T> C<T> newCollection(); } 

And I do not want to specify T in advance like this:

 public interface CollectionFactory<T, C extends Collection<T>> { public C newCollection(); } 

As far as I know, this is not possible.
Would anyone like to surprise me?

Also, like the appetizer, does anyone know if something like this is possible in ... Scala ?

+4
source share
2 answers

In Scala, you can use higher types if you want to parameterize both C and T in this way:

 // means that C has a single type parameter and C[T] extends Seq[T] whatever T is // or C[_] <: Seq[_] which means C[T] must extend Seq[Something] but not necessarily Seq[T] trait SeqFactory[C[T] <: Seq[T]] { def newSeq[T]: C[T] } 

Implementation Example:

 object ListFactory extends SeqFactory[List] { def newSeq[T] = List() } 

You are right that this cannot be done in Java, but depending on the purpose, the @Dylan or @CostiCiudatu solution may be good enough, even if they are less typical.

+4
source

Based on each invocation method, you can try something like:

 public interface CollectionFactory { public <T, C extends Collection<T>> C newCollection(); } 
+3
source

Source: https://habr.com/ru/post/1446001/


All Articles