What precisely is a scala evidence parameter

后端 未结 3 1956
独厮守ぢ
独厮守ぢ 2021-02-02 15:41

I\'ve been trying to find an authoritative definition of what is an evidence parameter, to no avail, for solving a case of \"could not find implicit value for evidence parameter

3条回答
  •  萌比男神i
    2021-02-02 16:28

    The language specification uses the term "evidence" in §7.4 Context Bounds and View Bounds:

    A type parameter A of a method or non-trait class may also have one or more context bounds A : T. In this case the type parameter may be instantiated to any type S for which evidence exists at the instantiation point that S satisfies the bound T. Such evidence consists of an implicit value with type T[S].

    With this syntactic sugar you get synthetic parameters which the spec calls "evidence parameters". (Note that this also covers view-bounds <% which are now deprecated).

    Since often explicitly written implicit parameters are also named evidence, I think it's valid to call any implicit parameter an "evidence" if it witnesses a specific property of a type. Take for example <:< [A, B] that evidences that A is a sub-type of B:

    trait Foo
    
    trait Bar[A] {
      def baz(implicit evidence: A <:< Foo): Unit
    }
    

    Then if you try this:

    trait Test {
      def bar: Bar[Any]
    
      bar.baz
    }
    

    This fails with a compilation error:

    :58: error: Cannot prove that Any <:< Foo.
             bar.baz
                 ^
    

    The exact wording can be specified with the implicitNotFound annotation. Without a specific code example, it's unclear what generates the "could not find implicit value for evidence parameter of type....".

    Here's an example of a custom message:

    @annotation.implicitNotFound(msg = "Oh noes! No type class for ${A}")
    trait MyTypeClass[A]
    
    trait Bar[A] {
      def baz(implicit evidence: MyTypeClass[A]): Unit
    }
    

    Then:

    trait Test {
      def bar: Bar[Any]
    
      bar.baz
    }
    

    Fails with the custom message:

    :58: error: Oh noes! No type class for Any
             bar.baz
                 ^
    

提交回复
热议问题