我有以下代码:进口implicits作为方法参数传递VS类的构造函数参数
case class Custom(value: Int)
case class Custom2(value: Float)
case class MappedEncoding[I, O](f: I => O)
trait Decoders {
type BaseDecoder[T] =() => T
type Decoder[T] <: BaseDecoder[T]
}
trait ConcreteDecoders extends Decoders {
type Decoder[T] = ConcreteDecoder[T]
case class ConcreteDecoder[T](decoder:() => T) extends BaseDecoder[T] {
def apply(): T = decoder()
}
implicit def optionDecoder[T](implicit d: Decoder[T]): Decoder[Option[T]] =
ConcreteDecoder[Option[T]](() => Some(d()))
implicit def mappedDecoder[I, O](implicit mapped: MappedEncoding[I, O], decoder: Decoder[I]): Decoder[O] =
ConcreteDecoder[O](() => mapped.f(decoder()))
implicit def intDecoder: Decoder[Int] = ConcreteDecoder[Int](() => 1)
implicit def floatDecoder: Decoder[Float] = ConcreteDecoder(() => 1)
}
class ConcreteContext extends ConcreteDecoders {
}
case class TestObject() {
implicit val customDecoder = MappedEncoding[Int, Custom](Custom)
implicit val custom2Encoder = MappedEncoding[Custom2, Float](_.value) // 1
implicit val custom2Decoder = MappedEncoding[Float, Custom2](Custom2)
def a(c: ConcreteContext): Unit = {
import c._
implicitly[Decoder[Option[Custom]]] // 2
// implicitly[Decoder[Float]] // 3
implicitly[Decoder[Option[Float]]]
()
}
}
object Main extends App {
implicit val c = new ConcreteContext()
TestObject().a(c)
// TestObject(a).()
}
而且它不会在斯卡拉2.11.8编译和2.12.0错误:
diverging implicit expansion for type c.Decoder[Option[Float]]
[error] starting with method intDecoder in trait ConcreteDecoders
[error] implicitly[Decoder[Option[Float]]]
使用-Xlog-implicits
选项提供长时间的输出,但最有趣的部分是:
floatDecoder is not a valid implicit value for c.Decoder[Float] because:
[info] diverging implicit expansion for type c.Decoder[T]
[info] starting with method intDecoder in trait ConcreteDecoders
[info] implicitly[Decoder[Option[Float]]]
将c: CustomContext
从方法参数移动到case类构造函数参数使其编译。我认为这可能会改变暗示搜索范围。
此外下列动作中的一个使其编译:
- 评论线标有注解
1
(==第1行) - 注释线2
- 取消注释线3
它看起来像解决implicitly[Decoder[Option[Custom]]]
叶斯卡拉编译器处于影响解决implicitly[Decoder[Option[Float]]]
的状态。
为什么会发生这种情况,如何在不移动c: ConcreteContext
的方法参数的情况下编译它?
P.S.这是重现问题的简化代码。真正的代码要复杂得多,我需要支持ConcreteContext
作为方法参数传递的情况。
的东西在这里肯定有鬼。这似乎与[SI-9625](https://issues.scala-lang.org/browse/SI-9625)有些相关。将方法参数变为构造函数参数时,该问题也会消失。在旁注中,将'Decoder'作为'Function0'的子类型可能也不是最好的想法。 –
@ Jasper-M由于http://stackoverflow.com/q/40391732/746347,我使'Decoder'成为'Function0'的一个子类型。 – mixel
显而易见的解决方法'val c0:c.type = c;在def a(c:ConcreteContext):Unit'里面导入c0._'就足够满足你的需求了? –