我使用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 _ => ...
}
编译错误为:
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 类型,但为什么它仍然给我 type Nothing 错误。我不想:
profile.getDefault().copy(...)
因为我确实需要复制配置文件而不是复制默认值,如果配置文件为Nothing,则将其删除。 怎么办?
过滤器不会改变类型。
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)
^
但是您也可以用不同的方式表达您的代码。