仓颉编程语言编程技巧-枚举类型

仓颉编程语言编程技巧-枚举类型

编码文章call10242025-06-04 14:53:0710A+A-

什么是枚举类型

在很多语言中都有 enum 类型(或者称枚举类型),但是不同语言中的 enum 类型的使用方式和表达能力均有所差异,仓颉中的 enum 类型可以理解为函数式编程语言中的代数数据类型(Algebraic Data Types)。


普通枚举类型

package cangjie_test

main() {
    println([TestEnum.A, TestEnum.B, TestEnum.C])
}

enum TestEnum <: ToString {
    | A
    | B
    | C

    public func toString(): String {
        match (this) {
            case A => "TestEnum.A"
            case B => "TestEnum.B"
            case C => "TestEnum.C"
        }
    }
}

输出

[TestEnum.A, TestEnum.B, TestEnum.C]


代数枚举类型

package cangjie_test

import std.format.Formatter

main() {
    println("Blue = ${ColorHex.Blue}")
    println("Orange = ${ColorHex.Combination2(ColorHex.Red, ColorHex.Yellow)}")
    println("Black = ${ColorHex.Combination3(ColorHex.Red, ColorHex.Yellow, ColorHex.Blue)}")
}

enum ColorHex <: ToString {
    | Red
    | Yellow
    | Blue
    | Combination2(ColorHex, ColorHex)
    | Combination3(ColorHex, ColorHex, ColorHex)

    public prop hex: Int { // 提供hex属性
        get() { // 只提供getter
            match (this) { // 利用模式匹配处理hex结果
                case Red => 0xFF0000
                case Yellow => 0x00FF00
                case Blue => 0x0000FF
                case Combination2(a, b) => a.hex + b.hex
                case Combination3(a, b, c) => a.hex + b.hex + c.hex
            }
        }
    }

    public func toString(): String {
        var v = this.hex.format("X") // 将整数类型转成16进制字符串
        if (v.size < 6) { // 高位补0
            v = ("0" * (6 - v.size)) + v
        }
        "0x${v}"
    }
}

输出

Blue = 0x0000FF
Orange = 0xFFFF00
Black = 0xFFFFFF
点击这里复制本文地址 以上内容由文彬编程网整理呈现,请务必在转载分享时注明本文地址!如对内容有疑问,请联系我们,谢谢!
qrcode

文彬编程网 © All Rights Reserved.  蜀ICP备2024111239号-4