I am experementing with scala type classes and came upon following problem. I created a class with multiple methods. Each methods has an implicit parameter B and returns an Either[A,B].
Type B is a converter where the caller can provide a custom object to wrap the response the way he needs it.
So here is the code
case class A( var value:String){
}
case class Converter[A]( value : (Map[String, String] ) => A )
object Converter{
implicit val AConverter = new Converter[A]( (x:Map[String, String]) => new A("Hello World") )
implicit val IntConverter = new Converter[Int]( (x:Map[String, String]) => 10 )
}
class API{
def method1[B : Converter] : Either[A, B] = {
Right( implicitly[Converter[B]].value(Map.empty))
}
def method2[B : Converter](name:String) : Either[A, B] = {
Right( implicitly[Converter[B]].value(Map.empty))
}
def method3[B : Converter](id:Int) : Either[A, B] = {
Right( implicitly[Converter[B]].value(Map.empty))
}
}
Now here is my trouble. I want to archieve following
Each method should be callable without worring about the implicit param B because there should be a default implementation somewhere be defined.
So i defined some implicits in the companion object but that does not solve my problem at all!
// Works due implicit definiton
println( new API().method1[A])
// Works due implicit definiton
println( new API().method1[Int])
// Works not but should
println( new API().method1)
I want to say the type of B for method1 is Converter[A] and the type of B for method2 is Converter[Int] if the caller does not provide it.
// Implementation should use my default Converter[A]
println( new API().method1)
I came across this question here
https://stackoverflow.com/a/29205892/452265
So how can i provide a default type if the type itself is not passed to the method at all like in the example. I need this per method not per class.