【问题标题】:Scala Option pattern matching with case class与案例类匹配的 Scala 选项模式
【发布时间】: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


    【解决方案1】:

    当您声明时:

    val users = List()
    

    编译器推断:

    val users: List[Nothing] = List()
    

    Nothing 没有 id 属性。但是当你指定 users 是 List[UserDbEntry] 并调用 lastOption 时,编译器可以理解 Option 中的元素是 UserDbEntry,它有一个 id 属性,因此编译就好了。考虑到空列表将返回None,即Option[Nothing]。

    【讨论】:

    • 解释它; None 是 Option[Nothing] 很好奇它的来源。谢谢
    • 基本上应该始终指定 type 。我认为我们应该避免将代码编写为 val users = List() 的做法。我们应该在编译时确定我们的类型。
    猜你喜欢
    • 1970-01-01
    • 2014-08-12
    • 2017-02-25
    • 1970-01-01
    • 1970-01-01
    • 2017-04-25
    • 1970-01-01
    • 2013-09-13
    • 1970-01-01
    相关资源
    最近更新 更多