简体   繁体   English

依赖的类和类型

[英]Dependent classes and types

Let's say that I want to create a simple graph representation where Vertex and Edge and their types depend on each other. 假设我想创建一个简单的图形表示形式,其中VertexEdge及其类型相互依赖。 A concrete implementation could look something like this: 一个具体的实现可能看起来像这样:

case class Edge(id: Int, label: String, endpoints: (Vertex, Vertex))
case class Vertex(id: Int, data: Data, edges: Map[Int, Edge])

Edge depends on Vertex and vice versa. Edge取决于Vertex ,反之亦然。 What I really want is for id , data etc to have generic types. 我真正想要的是iddata等具有通用类型。 And I wonder how to design this the best way? 我不知道如何设计最佳方法?

trait Vertex[A, B] {
  def id: A
  def data: B
  // What about types for the edges etc?
}

trait Edge[A, ...] {
  def id: A
  def label: String
  def endpoints: (Vertex[...], Vertex[...])
}

A simple example of this would be much appreciated. 一个简单的例子将不胜感激。

What is wrong with re-using the type parameters? 重新使用类型参数有什么问题?

trait Vertex[A, B] {
  def id: A
  def data: B
  def edges: Map[A, Edge[A, B]]
}

And then in Edge : 然后在Edge

trait Edge[A, B] {
  def id: A
  def label: String
  def endpoints: (Vertex[A, B], Vertex[A, B])
}

Since Vertex and Edge can have different ID types, you may want to have Vertex and Edge be inner traits of a Graph trait, which has all the type parameters. 由于Vertex和Edge可以具有不同的ID类型,因此您可能希望将Vertex和Edge作为具有所有类型参数的Graph特征的内部特征。 That way, Vertex can know about the Edge trait's ID type, and Edge can know about the Vertex trait's ID and Data types. 这样,Vertex可以知道Edge特征的ID类型,而Edge可以知道Vertex特征的ID和数据类型。

trait Graph[VertexID, EdgeID, Data] {

  trait Vertex {
    def id: VertexID
    def data: Data
    def edges: Map[EdgeID, Edge]
  }

  trait Edge {
    def id: EdgeID
    def label: String
    def endpoints: (Vertex, Vertex)
  }

}

Incidentally, due to path-dependent types, Edge would only be able to have endpoints which are in the same Graph, and Vertex would only be able to have edges which are in the same Graph. 顺便说一句,由于与路径有关的类型,Edge将只能具有同一图形中的端点,而Vertex将只能具有同一图形中的边缘。

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

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