我试图理解为什么一个隐式转换在一个案例中起作用,而在另一个案例中却没有。 这是一个例子:
case class Wrapper[T](wrapped: T)
trait Wrapping { implicit def wrapIt[T](x: Option[T]) = x.map(Wrapper(_))
class NotWorking extends Wrapping { def foo: Option[Wrapper[String]] = Some("foo") }
class Working extends Wrapping {
def foo: Option[Wrapper[String]] = {
val why = Some("foo")
why
}
}
基本上,我有一个隐含的转换 Option[T]
至 Option[Wrapper[T]]
,我正在尝试定义一个函数,它返回一个可选的字符串,它被隐式包装。
问题是为什么,当我试图返回时 Option[String]
直接(NotWorking
上面),我收到一个错误(found : String("foo") required: Wrapper[String]
),如果我在返回之前将结果分配给val,那就消失了。
是什么赋予了?