Scala: Implicit evidence for class with type parameter

后端 未结 3 1606
清歌不尽
清歌不尽 2021-02-14 07:20

Here is a simple setup with two traits, a class with a covariant type parameter bounded by the previous traits, and a second class with a type parameter bounded by the other cla

3条回答
  •  萌比男神i
    2021-02-14 07:45

    This is not an answer to the question, but to show that the 'type constraint' is really just an implicit conversion:

    Welcome to Scala version 2.9.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_33).
    Type in expressions to have them evaluated.
    Type :help for more information.
    
    scala> trait A { def test() {} }
    defined trait A
    
    scala> class WhatHappens[T] { def test(t: T)(implicit ev: T <:< A) = t.test() }
    defined class WhatHappens
    
    scala> :javap -v WhatHappens
    ...
    public void test(java.lang.Object, scala.Predef$$less$colon$less);
      Code:
       Stack=2, Locals=3, Args_size=3
       0:   aload_2
       1:   aload_1
       2:   invokeinterface #12,  2; //InterfaceMethod scala/Function1.apply:(Ljava/lang/Object;)Ljava/lang/Object;
       7:   checkcast   #14; //class A
       10:  invokeinterface #17,  1; //InterfaceMethod A.test:()V
       15:  return
    ...
      LocalVariableTable: 
       Start  Length  Slot  Name   Signature
       0      16      0    this       LWhatHappens;
       0      16      1    t       Ljava/lang/Object;
       0      16      2    ev       Lscala/Predef$$less$colon$less;
    ...
    

提交回复
热议问题