类型细化的隐式扩展方法
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]`
}
倒数第二行没问题,但最后一行不行。由于某种原因,编译器无法 link 使用 Aux
扩展类型类扩展方法。
有人可以解释这是为什么吗?
因为toAllOps
不是隐式的。
我似乎无法在 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]`
}
倒数第二行没问题,但最后一行不行。由于某种原因,编译器无法 link 使用 Aux
扩展类型类扩展方法。
有人可以解释这是为什么吗?
因为toAllOps
不是隐式的。