【发布时间】:2012-10-16 21:16:22
【问题描述】:
我正在尝试通过使用 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)
【问题讨论】:
-
你可以试试
super.execute[T, SQLiteJob[T]](job)吗? -
@RégisJean-Gilles 成功了!想把它作为答案吗?
-
尽管我的回答有误,但我仍然坚持我的建议:当您打算返回
Unit以外的其他内容时,最好在def something = {...}中使用=。 -
@Damian:当然。我没有立即添加它,因为我没有测试它。