You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Stumbled across this strange behavior, when working on generic functions using implicit objects.
The following code snippet works just fine:
object DecBeforeUseImplicit extends App {
trait Measure[A] {
def measure(a: A): Int
}
case class ConstrWorker(name: String, age: Int, weight: Int)
val andy = ConstrWorker("Andy", 25, 105)
def measure[A](a: A)(implicit measure: Measure[A]): Int =
measure.measure(a)
implicit object MeasureWorker extends Measure[ConstrWorker] {
override def measure(a: ConstrWorker): Int = a.weight
}
println(measure(andy))
}
But if I declare the implicit object after using measure, like this:
object DecBeforeUseImplicit extends App {
trait Measure[A] {
def measure(a: A): Int
}
case class ConstrWorker(name: String, age: Int, weight: Int)
val andy = ConstrWorker("Andy", 25, 105)
def measure[A](a: A)(implicit measure: Measure[A]): Int =
measure.measure(a)
println(measure(andy))
implicit object MeasureWorker extends Measure[ConstrWorker] {
override def measure(a: ConstrWorker): Int = a.weight
}
}
The compiler can't find the implicit value for parameter measure and therefore there aren't enough arguments for measure.
Error Message:
Error:(18, 18) could not find implicit value for parameter measure: DecBeforeUseImplicits.Measure[DecBeforeUseImplicits.ConstrWorker]
println(measure(andy))
Error:(18, 18) not enough arguments for method measure: (implicit measure: DecBeforeUseImplicits.Measure[DecBeforeUseImplicits.ConstrWorker])Int.
Unspecified value parameter measure.
println(measure(andy))
Stumbled across this strange behavior, when working on generic functions using implicit objects.
The following code snippet works just fine:
But if I declare the implicit object after using measure, like this:
The compiler can't find the implicit value for parameter measure and therefore there aren't enough arguments for measure.
Error Message:
Error:(18, 18) could not find implicit value for parameter measure: DecBeforeUseImplicits.Measure[DecBeforeUseImplicits.ConstrWorker]
println(measure(andy))
Error:(18, 18) not enough arguments for method measure: (implicit measure: DecBeforeUseImplicits.Measure[DecBeforeUseImplicits.ConstrWorker])Int.
Unspecified value parameter measure.
println(measure(andy))
Here is the file:
DecBeforeUseImplicits.zip
I'm using scala-sdk-2.13.0, JDK-11.0.3 and IntelliJ 2019.2.1 with Scala Plugin.
Maybe I'm totally wrong. If so, I'm very sorry and it'd be great, if you could link the part of the docs where the right way is mentioned.
The text was updated successfully, but these errors were encountered: