简体   繁体   English

Scala的路径相关类型是什么意思?

[英]What is meant by Scala's path-dependent types?

I've heard that Scala has path-dependent types. 我听说Scala具有依赖于路径的类型。 It's something to do with inner-classes but what does this actually mean and why do I care? 这与内部类有关,但这实际上意味着什么,为什么我要关心?

My favorite example: 我最喜欢的例子:

case class Board(length: Int, height: Int) {
  case class Coordinate(x: Int, y: Int) { 
    require(0 <= x && x < length && 0 <= y && y < height) 
  }
  val occupied = scala.collection.mutable.Set[Coordinate]()
}

val b1 = Board(20, 20)
val b2 = Board(30, 30)
val c1 = b1.Coordinate(15, 15)
val c2 = b2.Coordinate(25, 25)
b1.occupied += c1
b2.occupied += c2
// Next line doesn't compile
b1.occupied += c2

So, the type of Coordinate is dependent on the instance of Board from which it was instantiated. 因此, Coordinate的类型取决于实例化其的Board实例。 There are all sort of things that can be accomplished with this, giving a sort of type safety that is dependent on values and not types alone. 使用此方法可以完成所有事情,从而提供一种类型安全性,该类型安全性依赖于值而不是类型本身。

This might sound like dependent types, but it is more limited. 这听起来像是依赖类型,但它的局限性更大。 For example, the type of occupied is dependent on the value of Board . 例如, occupied的类型取决于Board的值。 Above, the last line doesn't work because the type of c2 is b2.Coordinate , while occupied 's type is Set[b1.Coordinate] . 在上面,最后一行不起作用,因为c2的类型是b2.Coordinate ,而occupied的类型是Set[b1.Coordinate] Note that one can use another identifier with the same type of b1 , so it is not the identifier b1 that is associated with the type. 注意,可以使用另一种具有相同b1类型的标识符,因此与该类型关联的不是标识符 b1 For example, the following works: 例如,以下工作:

val b3: b1.type = b1
val c3 = b3.Coordinate(10, 10)
b1.occupied += c3

"the path" means a path reference, here, types reference to object b1, b2. “路径”是指路径引用,这里是对象b1,b2的类型引用。

a path-dependent type reference an outer object, whereas an inner class type reference an outer class. 依赖于路径的类型引用外部对象,而内部类类型引用外部类。

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

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