【发布时间】:2016-03-29 11:56:30
【问题描述】:
我得到error: value id is not a member of Nothing
与case Some(x) => x.id。这不应该评估为 Some 类型。
case class UserDbEntry(id: Int, username: String)
val users = List()
val lastTableIds = "user.1::paypal.1"
val lastUserId = lastTableIds.split("::")(0).split("\\.")(1)
//This does not compile
val id = users.lastOption match {
case Some(x) => x.id
case None => lastUserId
}
//This compiles
def getLastFetchId(x: Option[UserDbEntry]) = x match {
case Some(user) => user
case None => 1
}
但是使用显式类型 List[UserDbEntry] 定义的 List 这很好,在这种情况下编译器会成功推断出这一点。我想这与编译器推断有关;如果我没记错的话。只是我预计如果存在类型不匹配,则会出现与 x 不是 String 类型的成员一致的错误。
这里到底发生了什么?
【问题讨论】:
标签: scala pattern-matching type-inference