Scala: implicit conversion does not work

I have a problem with an implicit function imported from a package.

I have a class that uses Regex to search for something in the text. I would like to use it like:

 val pattern = "some pattern here".r pattern findSomethingIn some_text 

To do this, I define an implicit finction to convert the pattern to a Wrapper wrapper that contains the findSomethingIn function

 package mypackage { class Wrapper ( val pattern: Regex ) { def findSomethingIn( text: String ): Something = ... } object Wrapper { implicit def regex2Something( pat: Regex ): Wrapper = new Wrapper( pat ) } } 

if i use it like

 import mypackage._ Wrapper.regex2Something( pattern ) findSomethingIn some_text 

it works. whereas if i use

 pattern findSomethingIn some_text // implicit should work here?? 

I get

 value findPriceIn is not a member of scala.util.amtching.Regex 

so the implicit conversion doesn’t work here ... What is the problem?

+6
source share
2 answers

You will need

 import mypackage.Wrapper._ 

to import the appropriate methods.

See this blog post for more information and note, in particular, the definition / import of the Conversions object.

+9
source

Brian's answer is better, although an alternative would be to use a package object

 package object mypackage { implicit def regex2Something( pat: Regex ): Wrapper = new Wrapper( pat ) } 

This will allow you to use the original import mypackage._ line, since the implicit def will be in the package itself.

http://www.scala-lang.org/docu/files/packageobjects/packageobjects.html

+3
source

Source: https://habr.com/ru/post/921838/


All Articles