繁体   English   中英

类型细化的隐式扩展方法

[英]implicit extension methods on type refinements

在scala 2.12.4中,我似乎无法获得隐式扩展方法来进行类型细化。 考虑以下:

trait MyTypeclass[A,B] {
  def foo[C](a : Test.Aux[A,B], c : C ) : Test.Aux[A,C]
}

object MyTypeclass {
  trait Ops[A,B] {
    def instance : MyTypeclass[A,B]
    def self : Test.Aux[A,B]
    def foo[C](c : C) : Test.Aux[A,C] = instance.foo[C](self,c)
  }

  object syntax {
    def toAllOps[A,B](t : Test.Aux[A,B])(implicit tc : MyTypeclass[A,B]) = new Ops[A,B] {
      val instance = tc
      val self = t
    }
  }
}

trait Test[A] {
  type B
}

object Test {

  type Aux[A,B0] = Test[A] { type B = B0 }

  def apply[A,B0] : Aux[A,B0] = new Test[A] { type B = B0 } 

  implicit def instance[A,B] : MyTypeclass[A,B] = new MyTypeclass[A,B] { 
    /** Does nothing more than change the second type `B` to the passed value `C` */
    def foo[C](a : Test.Aux[A,B], c : C) : Test.Aux[A,C] = new Test[A] { type B = C }
  }

  import MyTypeclass.syntax.toAllOps
  toAllOps(Test[String,Int]).foo(2.0)
  //Test[String,Int].foo(2.0) // ERROR : `foo is not a member of Test.Aux[String,Int]`
}

倒数第二行工作正常,但最后一行却不行。 由于某种原因,编译器无法将typeclass扩展方法与Aux链接起来。

有人可以解释为什么吗?

因为toAllOps不是隐式的。

暂无
暂无

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

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