1

我使用 scala 2.11.2。这是我的功能的一部分:

import scala.reflect.runtime.universe._
p => p.filter(p => typeOf[p.type] != typeOf[Nothing]).flatMap {
    case Some(profile) => {
        ...
        env.userService.save(profile.copy(passwordInfo = Some(hashed)),...) //<---------error here
    }
    case _ => ...
}

编译错误是:</p>

PasswordReset.scala:120: value copy is not a member of Nothing
[error]                   env.userService.save(profile.copy(passwordI
nfo = Some(hashed)), SaveMode.PasswordChange);
[error]                                                ^

我想我使用过滤器相位过滤了 Nothing 类型,但为什么它仍然给我类型 Nothing 错误。我不想:

profile.getDefault().copy(...)

因为我真的需要复制配置文件而不是复制默认值,所以如果配置文件是 Nothing 就删除它。怎么做?

4

1 回答 1

1

过滤器不会改变类型。

scala> def f[A](x: Option[A]) = x filter (_ != null)
f: [A](x: Option[A])Option[A]

Option[A]进来,Option[A]出去。

您建议过滤器函数中的运行时检查应指示编译器接受您的类型参数不是 Nothing,但这不是它的工作方式。

scala> f(None)
res2: Option[Nothing] = None

如果什么都没有被推断出来,那么什么都不是你得到的。

您希望防止编译器在某处推断 Nothing。有时需要提供显式类型参数来做到这一点:

scala> f[String](None)
res3: Option[String] = None

scala> f[String](None) map (_.length)
res4: Option[Int] = None

相比于

scala> f(None) map (_.length)
<console>:9: error: value length is not a member of Nothing
              f(None) map (_.length)
                             ^

但也有可能你可以用不同的方式表达你的代码。

于 2014-08-07T04:55:21.857 回答