Union types and Intersection types

前端 未结 4 2157
天命终不由人
天命终不由人 2020-12-13 02:39

What are the various use cases for union types and intersection types? There has been lately a lot of buzz about these type system features, yet somehow I have never felt ne

4条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-13 03:25

    For instance with union types one could describe json domain model without introducing actual new classes but using only type aliases.

    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(", ") + "]"
    }
    

提交回复
热议问题