scala - Is it possible to write typeclass with different implementations? -


this follow-up previous question

suppose have trait converterto , two implementations:

trait converterto[t] {   def convert(s: string): option[t] }  object converters1 {   implicit val toint: converterto[int] = ??? }  object converters2 {   implicit val toint: converterto[int] = ??? } 

i have 2 classes a1 , a2

class a1 {   def foo[t](s: string)(implicit ct: converterto[t]) = ct.convert(s)  }  class a2 {   def bar[t](s: string)(implicit ct: converterto[t]) = ct.convert(s) } 

now foo[t] call use converters1 , bar[t] call use converters2 without importing converters1 , converters2 in client code.

val a1 = new a1() val a2 = new a2() ... val = a1.foo[int]("0") // use converters1 without importing ... val j = a2.bar[int]("0") // use converters2 without importing 

can done in scala ?

import converters in class.

class a1 {  import converters1._  private def fooprivate[t](s: string)(implicit ct: converterto[t]) = ct.convert(s)   def fooshowntoclient[t](s: string) = fooprivate(s) } 

then use method, shown client

val a1 = new a1() a1.fooshowntoclient[int]("0") 

now client unaware of convertors.


Comments

Popular posts from this blog

Payment information shows nothing in one page checkout page magento -

tcpdump - How to check if server received packet (acknowledged) -