如何使用路径依赖类型类 [英] How to use a path dependent type class

查看:60
本文介绍了如何使用路径依赖类型类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在如下方法中使用依赖于类型的类型类:

I'm trying to use a type-dependent type class in a method as below:

@typeclass trait Identifiable[M] {
  type K
  def identify(id: M): K
}

object Identifiable {
  type Aux[M, K0] = Identifiable[M] { type K = K0 }
  implicit def identifiableTuple[K1, K2](
      implicit
      a: Identifiable[K1],
      b: Identifiable[K2]
  ): Identifiable.Aux[(K1, K2), (a.K, b.K)] = new Identifiable[(K1, K2)] {
    type K = (a.K, b.K)
    override def identify(id: (K1, K2)): K = {
      val k1 = a.identify(id._1)
      val k2 = b.identify(id._2)
      (k1, k2)
    }
  }

但是,当我尝试像下面这样使用它时,隐式参数没有解析

However, when I try to use it like bellow the implicit parameters is not resolved

def a[K: Identifiable](key:K) = { 
case k => 
 val keyString: String = the[Identifiable.Aux[K, String]].identify(key) 
case (k1,k2) => 
 val keyString: (String,String) = the[Identifiable.Aux[K, (String, String)]].identify(key) }

推荐答案

您要求在类型约束中使用依赖于路径的类型隐式,但随后又调用了该类型固定到某物的隐式.

You demand implicit with path-dependent type in type constraint but then you summon implicit with that type fixed to something.

为了让它工作,编译器必须能够证明 Identifiable 中的依赖类型等于 K,而在当前代码中它不能这样做.

For that to work compiler would have to be able to prove that dependent type in Identifiable is equal to K which in current code it cannot do.

你可以试试:

  • 在两个地方使用相同的约定(要么都带有 Aux,要么都带有依赖类型)
  • 用隐式证据证明依赖类型等于K ev: identifiable.K =:= K

这篇关于如何使用路径依赖类型类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆