scala 列表匹配
List(1,2) match {
case List(1,_) => println("1 in postion 1")
case _ => println("default")
}
编译/工作正常。 所以这样做
List(1) match ...
List(3,4,5) match ...
,但不这样做
List() match ...
会导致以下错误
found : Int(1)
required : Nothing
case List(1,_) => println("1 in postion 1")
为什么 List() 尝试匹配 List(1,_)?
List(1,2) match {
case List(1,_) => println("1 in postion 1")
case _ => println("default")
}
compiles / works fine.
So do
List(1) match ...
List(3,4,5) match ...
but not
List() match ...
which results in the following error
found : Int(1)
required : Nothing
case List(1,_) => println("1 in postion 1")
Why does List() try to match List(1,_)?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
List()
的类型为List[Nothing]
。如果您使用List[Int]()
它将按您的预期工作。(一般来说,类型具有尽可能多的限制性;由于您创建了一个其中没有任何内容的列表,因此使用最受限制的类型
Nothing
而不是Int如您所愿。)
List()
has typeList[Nothing]
. If you useList[Int]()
it will work as you expect.(In general, types are as restrictive as they can possibly be; since you have made a list with nothing in it, the most-restrictive-possible type
Nothing
is used instead ofInt
as you intended.)当您编写
List()
时,推断的类型是Nothing
,它是所有内容的子类型。发生的情况是,当您尝试不可能的匹配时,Scala 会给出错误。例如,
"abc" match { case 1 =>; }
将导致类似的错误。同样,由于可以静态确定List(1, _)
永远不会匹配List()
,因此 Scala 会给出错误。When you write
List()
, the type inferred isNothing
, which is subtype to everything.What is happening is that Scala gives an error when you try impossible matches. For example,
"abc" match { case 1 => }
will result in a similar error. Likewise, becauseList(1, _)
can be statically determined to never matchList()
, Scala gives an error.也许是因为...
Maybe because...