联合类型和交集类型的各种用例是什么?最近有很多关于这些类型系统功能的讨论,但不知何故,我从来没有觉得需要这些!
最佳答案
例如,使用联合类型可以描述 json 域模型,而无需引入实际的新类,而只使用类型别名。
type JObject = Map[String, JValue]
type JArray = List[JValue]
type JValue = String | Number | Bool | Null | JObject | JArray
type Json = JObject | JArray
def stringify(json: JValue): String = json match {
case String | Number | Bool | Null => json.toString()
case JObject => "{" + json.map(x y => x + ": " + stringify(y)).mkStr(", ") + "}"
case JArray => "[" + json.map(stringify).mkStr(", ") + "]"
}
关于programming-languages - 联合类型和交集类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5653678/