我正在使用scala中的java库。 java中有一个抽象类:
public abstract class SomeClass<I, O> implements Serializable {
public abstract class Context {
public abstract void output(O output)
}
public abstract class ProcessContext extends Context {
public abstract I element()
}
// method to override
public abstract void process(ProcessContext c) throws Exception
...
}
我试图在scala中创建一个子类:
class SubClass extends SomeClass[String, String] {
override def process(c: SubClass.this.type#ProcessContext) {
val elem = c.element()
// problem: elem is not recognized as a string
if (elem.trim.isEmpty) {...}
...
}
}
所以问题是类型参数有点丢失&#39;在scala子类中。 elem
变量未被识别为字符串。
我在http://www.somethingsimilar.com/2011/01/13/tricky-things-in-scala/看过Jeff Hodges的博客,并尝试过:
abstract class SSomeClass[I, O] extends DoFn[I, O] {
type Context = DoFn[I, O]#Context
type ProcessContext = DoFn[I, O]#ProcessContext
}
class SubClass extends SSomeClass[String, String] {
...
// same problem as before
}
但同样的问题仍然存在。
有什么建议吗?
谢谢!
答案 0 :(得分:1)
这表示element
的类型为String
。可能有更简单的方法来演示它。 (currentMirror reflect x).symbol
产生ClassSymbol。
package interop
import reflect.runtime._, universe._
class Subber extends SomeClass[String, String] {
override def process(c: SomeClass[String, String]#ProcessContext) = {
val x = c.element
debug(x)
}
def debug[A: TypeTag](a: A) = Console println implicitly[TypeTag[A]]
}
object Test extends App {
val s = new Subber()
val c = new s.ProcessContext { def element = "hi" ; def output(x: String) = () }
s process c
}