我想要一个提取器来隐式转换它的参数,但它似乎不起作用。考虑这个非常简单的案例:
case class MyString(s: String) {}
implicit def string2mystring(x: String): MyString = new MyString(x)
implicit def mystring2string(x: MyString) = x.s
object Apply {
def unapply(s: MyString): Option[String] = Some(s)
}
但我无法按预期使用它:
val Apply(z) = "a" // error: scrutinee is incompatible with pattern type
谁能解释为什么它无法将参数从转换String
为MyString
?我希望它会string2mystring("a")
即时调用。显然我可以通过说 来解决这个问题val Apply(y) = MyString("a")
,但似乎我不应该这样做。
注意:这个问题与这个问题类似,但是 1)对于为什么会发生这种情况并没有一个很好的答案,2)这个例子比它需要的更复杂。