2014-09-30 28 views
1

我在查看邊界時遇到了一些麻煩。我寫了下面的函數,它應該將任何對象seq作爲Seq[T]可見,如果它爲空則返回None,否則返回Some(seq)從數組[T]隱式轉換爲Seq [T]

def noneIfEmpty[T, S <% Seq[T]](seq: S): Option[S] = 
    if (seq.isEmpty) None else Some(seq) 

讓我們定義的功能...

scala> def noneIfEmpty[T, S <% Seq[T]](seq: S): Option[S] = ... 
noneIfEmpty: [T, S](seq: S)(implicit evidence$1: S => scala.collection.immutable.Seq[T])Option[S] 

好吧,函數簽名看起來正確。讓我們嘗試一個空列表...

scala> noneIfEmpty(List()) 
res54: Option[List[Nothing]] = None 

到目前爲止好。現在讓我們嘗試一個非空列表...

scala> noneIfEmpty(List(1,2,3)) 
res55: Option[List[Int]] = Some(List(1, 2, 3)) 

太好了。如何數組?

scala> noneIfEmpty(Array()) 
<console>:15: error: No implicit view available from Array[Nothing] => scala.collection.immutable.Seq[Any]. 
       noneIfEmpty(Array()) 
         ^

不太好。這裏發生了什麼?是不是有從Array[T]WrappedArray[T]的隱式轉換? scala.Predef.wrapRefArray不應該照顧這個?

+0

適用於2.11.2控制檯中的我。 – Ashalynd 2014-09-30 23:20:38

+0

同樣在這裏,你使用的是什麼版本的scala? – 2014-09-30 23:33:17

+1

它只是在'scala.collection.Seq'中工作,而不是在原始文章中爲'scala.collection.immutable.Seq'工作。我不認爲有'Array [T]'到'scala.collection.immutable.Seq [T]'的視圖... – 2014-09-30 23:55:32

回答

3

你有進口scala.collection.immutable.Seq的地方嗎?

有一個名爲系列隱觀*ArrayOpsscala.Predef其將Array[T]scala.collection.mutable.ArrayOps[T],但不immutable.Seq定義。

scala> def noneIfEmpty[S <% collection.Seq[_]](seq: S): Option[S] = 
    | if(seq.isEmpty) None else Some(seq) 
noneIfEmpty: [S](seq: S)(implicit evidence$1: S => Seq[_])Option[S] 

scala> noneIfEmpty(Array[Int]()) 
res0: Option[Array[Int]] = None 

scala> noneIfEmpty(Array[Int](1, 2, 3)) 
res1: Option[Array[Int]] = Some([[email protected]) 
相關問題