2012-10-16 12 views
0

我試圖通過使用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)

+2

你可以嘗試用'super.execute [T,SQLiteJob [T]](工作)'? –

+0

@RégisJean-Gilles工作!想把它作爲答案? – Damian

+0

儘管我錯誤的回答了,但我保留我的建議:當您有意返回「Unit」以外的內容時,在'def something = {...}'中使用'='是一個好習慣。 – pedrofurla

回答

3

指定類型參數調用執行時:

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