2014-07-09 136 views
2

我試圖寫一個簡單的工具斯卡拉通用上限

def withParLevel[T, Col <: ParIterable[T]](coll: Col, ts: TaskSupport): Col = { 
    coll.tasksupport = ts 
    coll 
} 
withParLevel(List(1,2,3,4,5).par, blockingPool) 

這給了我這個錯誤:

inferred type arguments [Nothing,scala.collection.parallel.immutable.ParSeq[Int]] do not conform to method withParLevel's type parameter bounds [T,Col <: scala.collection.parallel.ParIterable[T]] 

我該如何解決呢?

爲什麼它推斷T爲Nothing,而不是Int?

PS scala版本2.10.2

+0

好奇,我不知道爲什麼類型推斷在這裏失敗。我會等待有人解釋這一點。與此同時,將它改爲通配符('[T <:ParIterable [_]])或視圖綁定('[A,B <%ParIterable [A]]')似乎可行... –

+0

I' d完全刪除'Col'類型參數並使用子類型多形主義:'def withParLevel [T](coll:ParIterable [T]):ParIterable [T] = coll' –

回答

3

更改綁定到視圖綁定的類型。 Scala編譯器需要兩個類型參數之間的證據表明,列=> scala.collection.parallel.ParIterable [T]

讓我們快速REPL會話:(編譯我沒有使用TaskSupport PARAM)

$ scala 
Welcome to Scala version 2.10.4 (Java HotSpot(TM) 64-Bit Server VM, Java 1.8.0_05). 
Type in expressions to have them evaluated. 
Type :help for more information. 

scala> import scala.collection.parallel.ParIterable 
import scala.collection.parallel.ParIterable 

scala> def withParLevel[T, Col <: ParIterable[T]](coll: Col): Col = coll 
withParLevel: [T, Col <: scala.collection.parallel.ParIterable[T]](coll: Col)Col 

讓我們使用視圖邊界修復編譯錯誤:

scala> def withParLevel[T, Col <% ParIterable[T]](coll: Col): Col = coll 
withParLevel: [T, Col](coll: Col)(implicit evidence$1: Col => scala.collection.parallel.ParIterable[T])Col 

scala> withParLevel(List(1,2,3,4,5).par) 
res0: scala.collection.parallel.immutable.ParSeq[Int] = ParVector(1, 2, 3, 4, 5) 

編輯: 原因:如果類型界限的一個驅動另一個(在你的情況,山口派生自T中的推理),你需要查看邊界。

+0

似乎可行,但不清楚爲什麼類型綁定不起作用。所以一般的規則:如果你想要一些複雜的類型使用'<%'而不是'<:' – yura

+0

@yura:用實際原因更新了帖子。 –