Search code examples
scalaimplicit

Could not find implicit when used in main method


I've got code similar to the following extract:

object Obj {
  case class Dog(colour: String= "brown")

  def summon(dog: Dog = Dog()): Dog = dog

  def getColour(implicit d: Dog): String = d.colour

  def main(args: Array[String]): Unit = {
    implicit val dog = summon(Dog(colour = "orange"))

    val colour = getColour
  }
}

This doesn't compile because the compiler can't find an implicit dog for parameter d when calling getColour. The strange thing though is that if I try to assign the result of getColour to a val named something other than colour it works. Also if I move the 2 lines out of the main method it works as well. Any ideas what's causing the implicit resolution to fail here?

I'm using Scala version 2.12.6.


Solution

  • If we remove implicit like so

      def main(args: Array[String]): Unit = {
        val dog = summon(Dog(colour = "orange"))
        val colour = getColour(dog) // error: recursive value dog needs type
      }
    

    we get recursive value dog needs type, so I believe this is an instance of

    https://issues.scala-lang.org/browse/SI-5091