Home > Net >  Calling a generic scala method in groovy
Calling a generic scala method in groovy

Time:12-15

I am trying to call a method from an external scala library in a groovy class.

The library method has the signature:

def ofType[T: ClassTag](bundle: Bundle): Iterable[T]

The call ofType<Data>(bundle) results in the error Groovyc: unable to resolve class ofType <Data>

I can call other methods from this library without issue, is there a way to correctly call this method?

CodePudding user response:

def ofType[T: ClassTag](bundle: Bundle) 

is desugared into

def ofType[T](bundle: Bundle)(implicit ctag: ClassTag[T])

so you'll have to resolve implicit manually.

Try to call

obj.<Data>ofType(bundle, ClassTag.apply(Data.class))

or just

ofType(bundle, ClassTag.apply(Data.class))

I guess, in Groovy a type parameter is specified at a method call site like in Java as obj.<A>method(params), not as obj.method<A>(params).

Scala multiple parameter lists

def ofType[T](bundle: Bundle)(implicit ctag: ClassTag[T])
//            ^^^^^^^^^^^^^^  ^^^^^^^^^^^^^^^^^^^^^^^^^^

are seen in Java as a single parameter list. I guess this can be similar in Groovy.


Groovy-Scala interop of generics depends on the version of Groovy. In How to call a scala method from build.gradle file I noticed that in Groovy 3.0.5 all the following declarations work

import shapeless.*

$colon$colon l =
  new $colon$colon(1, new $colon$colon("a", new HNil$()))
$colon$colon<Int, $colon$colon> l =
  new $colon$colon(1, new $colon$colon("a", new HNil$()))
$colon$colon<Int, $colon$colon<String, HNil>> l =
  new $colon$colon(1, new $colon$colon("a", new HNil$()))
HList l =
  new $colon$colon(1, new $colon$colon("a", new HNil$()))
def l =
  new $colon$colon(1, new $colon$colon("a", new HNil$()))

while in Groovy 2.5.10 only the last 2 declarations work.

  • Related