简体   繁体   English

使用Scala泛型:Class [T]不接受参数

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

I have a Java application and I want to move to Scala. 我有一个Java应用程序,我想转移到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 ... ) 所以我有这个内部类(原始的内部类,您可以在这里找到: 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)): 但是我在我的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)? 我的Scala class MyListener是否正确定义,尤其是Class[T] ,因为我从Java代码中复制了它(请参阅Android API的超链接)?
  • What I have to do to get the new MyListener working? 我需要做些什么来让new MyListener工作?

Scala always uses square brackets for type parameters, so what you want to do is simply this: Scala总是使用方括号作为类型参数,所以你想要做的只是这样:

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"). 顺便说一句,令人困惑的诊断是因为classOf产生了一个java.lang.Class实例,它不是一个可以像函数或方法一样调用的值(“不带参数”)。 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. 请记住,Scala将始终尝试将类型参数推断为泛型,例如classOf ,奇怪的是,它在没有任何类型参数的情况下使用时成功。 It infers the type Nothing : 它推断出Nothing类型:

scala> classOf
res1: Class[Nothing] = null

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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