Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala: implicit conversion does not work

Tags:

scala

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?

like image 224
Jakub M. Avatar asked Aug 01 '12 10:08

Jakub M.


2 Answers

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.

like image 143
Brian Agnew Avatar answered Oct 04 '22 16:10

Brian Agnew


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

like image 37
Nick Avatar answered Oct 04 '22 17:10

Nick