召唤辅助类型的高阶类型,而不参考原始类型 [英] Summon Aux for higher-kinded type without reference to the original

查看:123
本文介绍了召唤辅助类型的高阶类型,而不参考原始类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将Aux模式与更高种类的类型一起使用,直到以后再不必指定更高种类的参数.这类似于此处中所述的SO问题,但有一个显着的不同,我正朝着相反的方向发展,即从隐式def返回到aux.

I am trying to use the Aux pattern with a higher kinded type and not have to specify the parameter of the higher-kinded type until afterward. This is similar to the SO question described here but with one significant difference, I'm going the other way around, i.e. from an implicit def back to an aux.

// The are types that I want to convert to various things
sealed trait ConversionType
trait CaseA extends ConversionType
object CaseA extends CaseA // In this case, convert to an optional
trait CaseB extends ConversionType
object CaseB extends CaseB // In this case, convert to a future etc...

trait Converter[Prefix] {
  type Paramd[_]
  def create[N](n:N): Paramd[N]
}

// Create the mechanism to convert from the cases, only doing case A for now...
object Converter {
  type Aux[Prefix, Ret[_]] = Converter[Prefix] { type Paramd[_] = Ret[_] }

  // *** Error happens here! ***
  def apply[Prefix](implicit p:Converter[Prefix]): Aux[Prefix, p.Paramd] = p

  implicit def makeOptionParamd: Aux[CaseA, Option] =
    new Converter[CaseA] {
      type Paramd[_] = Option[_]
      override def create[N](n:N): Paramd[N] = Option[N](n)
    }
}

// This seems to be fine...
val v = Converter.apply[CaseA].create("test")

在上面提到的行上出现以下编译错误:

I get the following compile error on the above noted line:

Error:(97, 78) type mismatch;
 found   : p.type (with underlying type Test.this.Converter[Prefix])
 required: Test.Converter.Aux[Prefix,p.Paramd]
    (which expands to)  Test.this.Converter[Prefix]{type Paramd[_] = p.Paramd[_]}
    def apply[Prefix](implicit p:Converter[Prefix]): Aux[Prefix, p.Paramd] = p

我在做什么错了?

推荐答案

您可能想要的是

object Converter {
  type Aux[Prefix, Ret[_]] = Converter[Prefix] { type Paramd[A] = Ret[A] }

  // compiles
  def apply[Prefix](implicit p:Converter[Prefix]): Aux[Prefix, p.Paramd] = p

  implicit def makeOptionParamd: Aux[CaseA, Option] =
    new Converter[CaseA] {
      type Paramd[A] = Option[A]
      override def create[N](n:N): Paramd[N] = Option[N](n)
    }
}

写作时

type Paramd[_] = Ret[_]

左右部分中的

_不相关.与

the _ in the left and the right parts are unrelated. It's the same as

type Paramd[A] = Ret[_]

type Paramd[A] = Ret[B] forSome { type B }

因此具有您定义的Aux[Prefix, p.Paramd]等同于Converter[Prefix] { type Paramd[A] = p.Paramd[_] },并且p没有这种类型,因为p.Paramd[A]不是p.Paramd[_].

So Aux[Prefix, p.Paramd] with your definition is equivalent to Converter[Prefix] { type Paramd[A] = p.Paramd[_] }, and p doesn't have this type because p.Paramd[A] is not p.Paramd[_].

这篇关于召唤辅助类型的高阶类型,而不参考原始类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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