Scala 的路径依赖类型是什么意思? [英] What is meant by Scala's path-dependent types?

查看:31
本文介绍了Scala 的路径依赖类型是什么意思?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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?

推荐答案

我最喜欢的例子:

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

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

So, the type of Coordinate is dependent on the instance of Board from 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.

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

This might sound like dependent types, but it is more limited. For example, the type of occupied is dependent on the value of Board. Above, the last line doesn't work because the type of c2 is 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 identifier b1 that is associated with the type. For example, the following works:

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

这篇关于Scala 的路径依赖类型是什么意思?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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