用抽象类型交换类型参数 [英] Exchanging type parameters with abstract types

查看:49
本文介绍了用抽象类型交换类型参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了避免在对参数化类进行子类化时重复类型参数信息,我尝试重写一些代码以使用抽象类型.

To avoid having to repeat type parameter information when subclassing parameterized classes, I'm trying to rewrite some code to use abstract types instead.

我想表达的类似于:

class Group[A]

abstract class Thing[A, G <: Group[A]] {
  val group: G
}

class SomeGroup[A] extends Group[A] { g =>    
  object SomeThing extends Thing[A, SomeGroup[A]] {
    val group = g
  }
}

使用抽象类型,我目前最好的尝试是:

Using abstract types, my best attempt so far is:

class Group {
  type A
}

abstract class Thing { t =>
  type A
  type G <: Group { type A = t.A }
  val group: G
}

class SomeGroup extends Group { g =>
  object SomeThing extends Thing {
    type A = g.A
    type G = SomeGroup { type A = g.A }
    val group = g
  }
}

但是,我在最后一行收到编译器错误,提示值组具有不兼容的类型".

However, I'm getting a compiler error on the last line saying "value group has incompatible type".

如何使用抽象类型编写第一个示例?

推荐答案

你需要给类型检查器/推断器一些帮助:

You need to give the type checker/inferrer a little help:

val group : G = g

让它通过.

这篇关于用抽象类型交换类型参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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