我使用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类型的过滤器阶段过滤器,但为什么它仍然给我类型Nothing错误。我不想:
profile.getDefault().copy(...)
因为我真的需要复制配置文件而不是复制默认值,如果配置文件是Nothing只是删除它。 怎么做?
答案 0 :(得分:0)
过滤器不会更改类型。
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。有时需要提供显式类型的args来执行此操作:
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)
^
但您也可以用不同的方式表达您的代码。