【发布时间】:2016-09-18 16:53:46
【问题描述】:
我是 Scala 语言的新手 - 我似乎很难找到正确的语法来排序和比较两个 Option[Seq[String]]。无论内容顺序如何,两者都应该相等。此测试的最后一行失败。我希望这段代码充分记录了这个问题。
package seqtest
import org.scalatest.{Matchers, FlatSpec}
class SortCollectionsTest extends FlatSpec with Matchers {
"Different seq order" should "not affect equality" in {
val seqAB1 = Seq("A","B")
val seqAB2 = Seq("A","B")
// two different sequences are equal
assert(seqAB1 == seqAB2)
val seqBA1 = Seq("B","A")
// two different sequences are not equal if different order
assert(seqAB1 != seqBA1)
// but is possible to convert sequence to list and sort
assert(seqAB1.toList.sorted == seqBA1.toList.sorted)
// now do the same thing with Option
val someSeqAB1 = Some(Seq("A","B"))
val someSeqAB2 = Some(Seq("A","B"))
// two different option sequences are equal
assert(someSeqAB1 == someSeqAB2)
val someSeqBA = Some(Seq("B","A"))
// two different optional sequences are not equal if different order
assert(someSeqAB1 != someSeqBA)
// Option can be converted into list (unsorted)
assert(someSeqAB1.toList != someSeqBA.toList)
// problem
// two different optional sequences cannot be sorted
// compilation error
// Error:(42, 30) No implicit Ordering defined for Seq[String].
// Error:(42, 30) not enough arguments for method sorted: (implicit ord: scala.math.Ordering[Seq[String]])List[Seq[String]].
// Unspecified value parameter ord.
assert(someSeqAB1.toList.sorted == someSeqBA.toList.sorted)
}
}
【问题讨论】:
-
嗯,我的 StackOverflow 代码格式似乎也有问题。 ..
-
当您执行
someSeqAB1.toList时,您将获得List[Seq[String]]。尝试对此列表进行排序时遇到错误,因为Seq[String]没有定义隐式排序。 -
someSeqAB1.toList编译是因为Option是Iterable,由这种隐式转换引起:scala.Option#option2Iterable。Option.toList在Option.isDefined时为您提供单例List,否则为空列表。欢迎来到 Scala。 -
在完成了不同的转换之后,我现在有以下可以编译和工作的
assert(someSeqAB1.getOrElse(Seq("")).toList.sorted == someSeqBA.getOrElse(Seq("")).toList.sorted)
标签: scala collections