B. Smith
B. Smith

Reputation: 1193

Why does scala method not accept generic?

I have the following 2 methods:

def callAlpha = call[T](Constants.Alpha)(_: String)(_: T => T)

def call[T](symbol: String)(caller: String)(op: T => T)(implicit ct: ClassTag[T]): String = { // some code }

Eclipse complains about the use of generics in the first method, but not in the second. Why is this?

Upvotes: 0

Views: 48

Answers (2)

Andrey Tyukin
Andrey Tyukin

Reputation: 44908

Because in

def callAlpha = call[T](Constants.Alpha)(_: String)(_: T => T)

there is an unbound type variable T on the right hand side.

You probably meant:

def callAlpha[T] = call(Constants.Alpha)(_: String)(_: T => T)

Upvotes: 2

Tzach Zohar
Tzach Zohar

Reputation: 37822

In the second method you include a type parameter definition ([T] which immediately follows the method name). This declares a type parameter named T (you can name it however you want) which can then be used in the method's input arguments, output type, and implementation.

The first method is missing this definition - it attempts to use a type named T without declaring such a type: the method name (callAlpha) is not followed by a similar type parameter definition and therefore the method body (call[T](Constants.Alpha)(_: String)(_: T -> T)) cannot use it.

The fix can be simple - define T for the first method too:

def callAlpha[T] = call[T](Constants.Alpha)(_: String)(_: T => T)

Upvotes: 3

Related Questions