I have a problem with implicit
function, imported from a package.
I have a class that uses Regex to find something in a text. I would like to use it as:
val pattern = "some pattern here".r
pattern findSomethingIn some_text
To do so, I define an implicit
finction to convert pattern
to a wrapper Wrapper
that contains 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 as
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 does not work here... What is the problem?
You will need
import mypackage.Wrapper._
to import the appropriate methods.
See this blog entry for more info, and note in particular the definition/import of the Conversions
object.
Brian's answer is best, though 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 your original import mypackage._
line, as the implicit def will be in the package itself.
http://www.scala-lang.org/docu/files/packageobjects/packageobjects.html
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With