John Threepwood
John Threepwood

Reputation: 16143

Is it possible to define a return type with an arbitrary type parameter?

Assume, we have a a class with an type parameter

class A[T]

And we want to write a method, that returns objects of the type A with an arbritrary type parameter, like:

def f: A = { ... }

The compiler will complain about the missing type parameter for type A.

We can not solve this problem by writing A[Any], since e.g. A[String] is no subtype of A[Any]. But we can reach this subtype relation with a covariant annotation of +T.

Is it possible write such a method f without using covariant annotation +T ?

Upvotes: 0

Views: 114

Answers (1)

oxbow_lakes
oxbow_lakes

Reputation: 134330

You can use existential types:

def f: A[_] = { ... }

This is shorthand for:

def f: A[T forSome { type T }] = { ... }

You can even use upper (or lower) bounds:

def f: A[_ <: SomeType] = { ... }

You can assign any type T to this, however, you may not be able to do anything useful with the result

Upvotes: 4

Related Questions