[英]Scala list match for type and size
I'm trying to do some patting matching in Scala and I'm running into some problems. 我正在尝试在Scala中进行一些匹配,但遇到了一些问题。 Here's my code (minus the fluff):
这是我的代码(减去绒毛):
realtionships.filter(...) match {
case (parent: Relationship) :: Nil => parent.endNode
case _ => throw new Exception
}
The gist is that I want a list that is only a single item that is of type Relationship
. 要点是,我想要一个列表,该列表仅是
Relationship
类型的单个项目。 If it's anything else, throw an Exception. 如果还有其他问题,请抛出异常。 But the compiler is giving me this error:
但是编译器给我这个错误:
constructor cannot be instantiated to expected type
found: scala.collection.immutable.::[B]
required: scala.collection.immutable.Set[Relationship]
Why exactly am I getting this error? 为什么我会收到此错误? Am I not allowed to match the elements of a list while also trying to match the type?
在尝试匹配类型时,我是否不能匹配列表中的元素? Or do I just have the wrong syntax?
还是我语法错误? (Side note: Relationship is a case class.)
(旁注:关系是案例类。)
The compiler will refuse a pattern match if it can deduce that you are trying to match types which cannot be equal. 如果编译器可以推断出您试图匹配的类型不能相等,则它将拒绝模式匹配。 From the error message is appears that
relationships
is a Set
and you are trying to match for a List
. 从错误消息中会出现
relationships
是一个Set
而您正在尝试匹配一个List
。 Now a Set
can never be a List
, so the compiler rightfully rejects that code. 现在,
Set
永远不能是List
,因此编译器正确地拒绝了该代码。
If you want a List
actually, you can enforce it: 如果您实际上想要一个
List
,则可以执行它:
relationships.filter(...).toList match {
..
}
If you want to stick to a Set
, you would need an extractor on Set
. 如果要坚持使用
Set
,则需要Set
上的提取器。 That doesn't exist, however... Here is a question related with an answer that shows you to write a custom extractor. 但是,这不存在... 这是一个与答案相关的问题,向您展示了如何编写自定义提取器。 If you don't want to go through this effort, a poor man's solution would be
如果您不想付出这种努力,那么穷人的解决方案就是
val f = relationships.filter(...)
f.headOption match {
case Some(parent: Relationship) if f.size == 1 => parent.endNode
case _ => throw new Exception
}
(Note however that size
is an O(N) operation) (但是请注意,
size
是O(N)运算)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.