Scala-隐式转换,不应用 [英] Scala - implicit conversion with unapply

查看:123
本文介绍了Scala-隐式转换,不应用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望提取器可以隐式地转换其参数,但是它似乎不起作用.考虑这个非常简单的情况:

I'd like an extractor to implicitly convert its parameters, but it doesn't seem to work. Consider this very simple case:

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)
}

但是我无法像我期望的那样使用它:

But I'm not able to use it as I would expect:

val Apply(z) = "a"  // error: scrutinee is incompatible with pattern type

任何人都可以解释为什么它无法将参数从String转换为MyString的原因吗?我希望它能即时调用string2mystring("a").显然我可以通过说出val Apply(y) = MyString("a")来解决该问题,但是看来我不必这样做.

Can anyone explain why it fails to convert the parameter from String to MyString? I would expect it to call string2mystring("a") on the fly. Clearly I could work around the issue by saying val Apply(y) = MyString("a"), but it doesn't seem like I should have to do that.

注意:此问题类似于

Note: This question is similar to this one, but 1) that one doesn't really have a good answer for why this is happening, 2) the example is more complex than it needs to be.

推荐答案

模式匹配时不应用隐式转换.这不是代码的错误或问题,而仅仅是Scala的创建者的设计决定.

Implicit conversions are not applied when pattern matching. That's not a bug or a problem with your code, it's simply a design decision of the creators of Scala.

要解决此问题,您应该编写另一个接受String的提取器,该提取器又可以调用您的隐式转换.

To fix it, you should write another extractor that accepts a String — which in turn can call your implicit conversion.

或者,您可以尝试使用视图绑定,这似乎也可以使用,并且如果以后定义其他对MyString的隐式转换,也可以使用:

Alternatively, you can try with a view bound, which seems to work as well, and will also work if you later define other implicit conversions to MyString:

object Apply {
  def unapply[S <% MyString](s: S): Option[String] = Some(s.s)
}

这篇关于Scala-隐式转换,不应用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆