Scala 的路径依赖类型是什么意思?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2693067/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-22 02:06:06  来源:igfitidea点击:

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

scalatype-systemspath-dependent-type

提问by oxbow_lakes

I've heard that Scala has path-dependent types. It's something to do with inner-classes but what does this actually mean and why do I care?

我听说 Scala 有依赖于路径的类型。这与内部类有关,但这实际上意味着什么,我为什么要关心?

回答by Daniel C. Sobral

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 Coordinateis dependent on the instance of Boardfrom which it was instantiated. 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.

因此,的类型Coordinate取决于实例Board化它的实例。有各种各样的事情可以用这个来完成,提供一种依赖于值而不是单独类型的类型安全。

This might sound like dependent types, but it is more limited. For example, the type of occupiedis dependent on the value of Board. Above, the last line doesn't work because the type of c2is b2.Coordinate, while occupied's type is Set[b1.Coordinate]. Note that one can use another identifier with the same type of b1, so it is not the identifierb1that is associated with the type. For example, the following works:

这听起来像是依赖类型,但它更受限制。例如, 的类型occupied取决于 的值Board。上面,最后一行不起作用,因为 的类型c2b2.Coordinate,而occupied的类型是Set[b1.Coordinate]。请注意,可以使用与 相同类型的另一个标识符b1,因此与该类型关联的标识符不是b1。例如,以下工作:

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