scala - Impicit function can't be injected -


i have following code:

case class number (value:int) 

and

class calculator {   def performcalc( input:number)(implicit calc: (number=>number) ) =  calc(input) } 

now, when i, in specs2 test try this:

class calculatortest extends mutable.specification {   "calculator" should {     "*  accept explicit calculation parameter" in {       implicit val addtwelve = (input: number) => number(input.value + 12)       val calc = new calculator()        val result = calc.performcalc(number(4))       result must beequalto(16)     }   } } 

i expected 'addtwelve' function injected implicitly parameter of performcalc. however, following failure:

error:(49, 42) ambiguous implicit values:  both method $conforms in object predef of type [a]=> <:<[a,a]  , value addtwelve of type nl.example.number => nl.example.number  match expected type nl.example.number => nl.example.number       val result = calc.performcalc(number(4))                              ^ 

what doing wrong? should possible use methods implicits, right?

scala: 2.11.7

yes technically valid use of implicit, it's not strong use case. specifically, there pre-existing implicit provides number=>number. compiler having trouble telling implicit method really want.

what's better wrap method trait "tag" implicit type.

case class number(value: int) trait calcmethod {   def perform(n: number): number } class calculator {   def performcalc(input:number)(implicit calc: calcmethod) = calc.perform(input) }  class calculatortest extends mutable.specification {   "calculator" should {     "*  accept explicit calculation parameter" in {       implicit val addtwelve: calcmethod = new calcmethod {            def perform(input: number) = number(input.value + 12)        }       val result = new calculator().performcalc(number(4))       result must beequalto(16)     }   } } 

edit:

this maybe closer want:

case class number(value: int) implicit class calcmethod(val perform: number => number) class calculator {   def performcalc(input:number)(implicit calc: calcmethod) = calc.perform(input) } 

then can use so:

implicit val addtwelve: calcmethod = (input: number) => number(input.value + 12)  val result = new calculator().performcalc(number(4)) 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -