Skip to content

Implicit objects must be declared before use #11751

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
Babofett opened this issue Sep 26, 2019 · 2 comments
Closed

Implicit objects must be declared before use #11751

Babofett opened this issue Sep 26, 2019 · 2 comments

Comments

@Babofett
Copy link

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))

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.

@Jasper-M
Copy link

I think #8697 is the canonical ticket for this issue.

@eed3si9n
Copy link
Member

I am going to close this as duplicate then.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants