Scala - implicit conversion with unacceptable

I would like the extractor to implicitly convert its parameters, but it does not 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) = xs object Apply { def unapply(s: MyString): Option[String] = Some(s) } 

But I cannot use it as I expected:

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

Can someone explain why it cannot convert the parameter from String to MyString ? I expected him to call string2mystring("a") on the fly. It is clear that I could solve the problem by saying val Apply(y) = MyString("a") , but it seems to me that I should not do this.

Note. This question is similar to this , but 1) that there really is no good answer why this is happening, 2) the example is more complex than it should be.

+8
scala implicit conversion
source share
1 answer

Implicit conversions are not applied when matching patterns. This is not a mistake or a problem with your code, it is just a design decision by the creators of Scala.

To fix this, you must write another extractor that takes a String , which in turn can cause your implicit conversion.

Alternatively, you can try with a view binding, which seems to work too, and will also work if you later define other implicit conversions on MyString :

 object Apply { def unapply[S <% MyString](s: S): Option[String] = Some(ss) } 
+14
source share