Scala implicits resolution mechanism is declaration order dependent?

喜夏-厌秋 提交于 2019-12-01 08:54:52

问题


During daily Scala coding I faced an issue that Scala implicits resolution depends on declaration order. A simple example:

object example extends App {
  trait FooTypeClass[T] {
    def foo: T
  }

  def bar[T](implicit tc: FooTypeClass[T]) = println(tc.foo)

  class A {
    // bar[A] doesn't compile
  }
  object A {
    implicit object aFoo extends FooTypeClass[A] {
      def foo: A = new A { override def toString = "a" }
    }
  }

  bar[A]
}

It does compile, but if I uncomment the commented line, it won't find the required implicit in scope. So, to make it compile I should place object A declaration before class A. That means my companions should go before their classes but I'd rather leave them as they are in the example.

Why does this order matter? Is there a workaround for this?


回答1:


A possible workaround keeping the order you wished:

object A {
    implicit val aFoo: FooTypeClass[A] = new FooTypeClass[A] {
      def foo: A = new A {
        override def toString = "a"
      }
    }
  }

I keep on seeking for the explanation why object (instead of val) doesn't fit.



来源:https://stackoverflow.com/questions/20380800/scala-implicits-resolution-mechanism-is-declaration-order-dependent

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!