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
不應該照顧這個?
適用於2.11.2控制檯中的我。 – Ashalynd 2014-09-30 23:20:38
同樣在這裏,你使用的是什麼版本的scala? – 2014-09-30 23:33:17
它只是在'scala.collection.Seq'中工作,而不是在原始文章中爲'scala.collection.immutable.Seq'工作。我不認爲有'Array [T]'到'scala.collection.immutable.Seq [T]'的視圖... – 2014-09-30 23:55:32