简体   繁体   中英

Using Scala generics: Class[T] does not take parameters

I have a Java application and I want to move to Scala. So I have this inner class (the original one, you can find here: http://developer.android.com/reference/android/app/ActionBar.html#newTab() : public static class TabListener ... )

class MyListener[T <: MySuperClass]
    (var myClass: Class[T], ...) 
    extends MyActionListener { ... }

My problem is, how to call this class. I tried this:

myObject.setMyListener(
    new MyListener[MySubClassOfMySuperClass]
    (classOf(MySubClassOfMySuperClass), ...));

But I get the error in my IDE (classOf(MySubClassOfMySuperClass)):

Class[T] does not take parameters

So, I have two questions:

  • Is my Scala class MyListener defined correctly, especially Class[T] , because I copied this from Java code (see hyperlink of the Android API)?
  • What I have to do to get the new MyListener working?

Scala always uses square brackets for type parameters, so what you want to do is simply this:

myObject.setMyListener(new MyListener[MySubClassOfMySuperClass]
                           (classOf[MySubClassOfMySuperClass],  ...));

By the way, the confusing diagnostic is because classOf , which yields an instance of java.lang.Class , is not a value that can be invoked like a function or method ("does not take parameters"). Remember that Scala will always try to infer type parameters to generics such as classOf and oddly enough, it does so successfully when used without any type parameters. It infers the type Nothing :

scala> classOf
res1: Class[Nothing] = null

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM