[英]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: 因此,我有两个问题:
class MyListener
defined correctly, especially Class[T]
, because I copied this from Java code (see hyperlink of the Android API)? class MyListener
是否正确定义,尤其是Class[T]
,因为我从Java代码中复制了它(请参阅Android API的超链接)? 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.