ビューの境界に問題があります。次の関数を作成しました。これは、seq
表示可能なオブジェクトを として受け取り、それが空の場合はSeq[T]
返す必要があります。None
Some(seq)
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
これは気をつけないといけませんか?