7

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?

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

Comments

3

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.