Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error passing generic values to method using implicit parameter in Scala

Tags:

scala

implicit

I have implemented the following code in Scala

trait Implicit[A,B] { def method1(a:A, b:B) : Boolean }

object Implicit {
    implicit object IntImplicit extends Implicit[Int,Int] {
        override def method1(a: Int, b: Int): Boolean = a == b
    }
}

object Main
{
    def main(args:Array[String]) : Unit =
    {
        println(test(4,3))
    }

    def test[A,B](a:A, b:B)(implicit i: Implicit[A,B]) : Boolean =
        i.method1(a,b)
}

and it actually works fine. But if I define the following function

def jump[A,B](a:A, b:B) : Boolean = test(a,b)

into the Main object, it tells me that there is not "enough arguments for method test". I suppose that it's because it is not able to define the actual implicit value at compile time. Is it true or the problem is something else? If yes, how can I solve this problem?

Obviously this is just a simplification of the problem in order to replicate a condition where I have to call a method that declares an implicit parameter not previously knowing the actual types.

like image 695
Cattani Simone Avatar asked Dec 20 '25 06:12

Cattani Simone


1 Answers

The error you should be getting is:

scala> def jump[A, B](a: A, b: B) : Boolean = test(a, b)
<console>:14: error: could not find implicit value for parameter i: Implicit[A,B]
       def jump[A, B](a: A, b: B) : Boolean = test(a, b)
                                               ^

In order to call test with a generic A and B, the compiler needs to be able to find an implicit instance of Implicit[A, B]. Since A and B can be anything, the only way the compiler can find such an implicit for test is if you require the same implicit for jump:

def jump[A, B](a: A, b: B)(implicit i: Implicit[A, B]) : Boolean = test(a, b)
like image 58
Michael Zajac Avatar answered Dec 21 '25 22:12

Michael Zajac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!