我是 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)
}
}
最佳答案
我认为更简单的解决方案是映射选项:
assert(someSeqAB1.map{ _.sorted } == someSeqBA.map{ _.sorted })
顺便说一句,对于排序版本来说,断言是相等的。
关于Scala - 比较两个选项[Seq[String]],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39560262/