【问题标题】:Scala wrap generic anonymous classScala 包装通用匿名类
【发布时间】: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 &lt;T, J extends SQLiteJob&lt;T&gt;&gt; J execute(J job)

【问题讨论】:

  • 你可以试试super.execute[T, SQLiteJob[T]](job) 吗?
  • @RégisJean-Gilles 成功了!想把它作为答案吗?
  • 尽管我的回答有误,但我仍然坚持我的建议:当您打算返回 Unit 以外的其他内容时,最好在 def something = {...} 中使用 =
  • @Damian:当然。我没有立即添加它,因为我没有测试它。

标签: java scala closures


【解决方案1】:

调用execute时指定类型参数:

super.execute[T, SQLiteJob[T]](job)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多