简体   繁体   English

具有优先级隐式的上下文边界的类型错误

[英]Type Error for Context Bounding with Priority Implicits

I have the following issue, and I am confused as to what is going:我有以下问题,我对发生的事情感到困惑:

  1. I have a priority implicit defined我有一个隐式定义的优先级
  2. I use this priority implicit to impose a context bound我使用此优先级隐式来强加上下文绑定
  3. I declare a case class with a default field, which has values that are covered by the context bound我声明了一个带有默认字段的案例 class,该字段的值被上下文绑定所覆盖
  4. I am still getting a type error我仍然收到类型错误

A minimal working example which reflects the actual code I am working on.一个反映我正在处理的实际代码的最小工作示例。 I basically need the priority implicits in other part of my code:我基本上需要在我的代码的其他部分隐含优先级:

    // priority implicits
    sealed trait Stringifier[T] {
      def stringify(lst: List[T]): String
    }
    
    trait Int_Stringifier {
      implicit object IntStringifier {
        def stringify(lst: List[Int]): String = lst.toString()
      }
    }
    
    object Double_Stringifier extends Int_Stringifier {
      implicit object DoubleStringifier extends Stringifier[Double] {
        def stringify(lst: List[Double]): String = lst.toString()
      }
    }
    
    object Example extends App {
    
      trait Animal[T0] {
        def incrementAge(): Animal[T0]
      }
    
      case class Dog[T0: Stringifier]
      (age: Int = 0, locations: List[T0] = List(1, 2, 3)) extends Animal[String] {
        def incrementAge(): Dog[T0] = this.copy(age = age + 1)
      }
    }
 val t = Dog(age = 100)

I get a type mismatch error:我收到类型不匹配错误:

required List[T0]

found List[Int]

What is going on here?这里发生了什么? I reasoned that since I am creating my default parameters within the bound, the type should match.我推断,由于我在边界内创建默认参数,因此类型应该匹配。 Am I missing some trick here to make this work?我在这里错过了一些技巧来完成这项工作吗?

It's not clear how to reproduce your compile error目前尚不清楚如何重现您的编译错误

required List[T0]

found List[Int]

The code you added您添加的代码

val t = Dog(age = 100)

produces a different error产生不同的错误

Error: could not find implicit value for evidence parameter of type App.Stringifier[Int]
Error occurred in an application involving default arguments.
    val t = Dog(age = 100)

This is because you missed extends Stringifier[Int] and import Double_Stringifier._这是因为您错过了extends Stringifier[Int]import Double_Stringifier._

trait Int_Stringifier {
  implicit object IntStringifier extends Stringifier[Int] {
    def stringify(lst: List[Int]): String = lst.toString()
  }
}

import Double_Stringifier._

val t = Dog(age = 100) // compiles

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM