我试图通过使用 scala 闭包来使这段代码变得更好:
SQLiteQueue queue = new SQLiteQueue(databaseFile);
queue.start();
queue.execute(new SQLiteJob<Object>() {
protected Object job(SQLiteConnection connection) throws SQLiteException {
connection.exec(...);
return null;
}
});
我对 SQLiteQueue 进行了子类化,并向执行函数添加了重载:
def execute[T](action: SQLiteConnection => T) {
val job = new SQLiteJob[T] {
override def job(conn:SQLiteConnection):T = {
action(conn)
}
}
super.execute(job)
}
所以我可以像这样使用它:
queue.execute { conn => do something with conn}
但是我在 super.execute(job)
处收到此编译器错误
error: inferred type arguments [Nothing,com.almworks.sqlite4java.SQLiteJob[T]]
do not conform to method execute's type parameter bounds [T,J <:
com.almworks.sqlite4java.SQLiteJob[T]]
我在那里调用的执行函数如下所示:public <T, J extends SQLiteJob<T>> J execute(J job)
最佳答案
调用execute时指定参数类型:
super.execute[T, SQLiteJob[T]](job)
关于java - Scala 包装通用匿名类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12923538/