Kotlin 中命名构造函数的惯用方式

Tho*_* S. 3 kotlin

在Java中我有以下课程

public class Instruction {

    public static Instruction label(String name) {
        return new Instruction(Kind.label, name, null, 0);
    }

    public static Instruction literal(int value) {
        return new Instruction(Kind.intLiteral, null, null, value);
    }

    public static Instruction literal(boolean value) {
        return new Instruction(Kind.boolLiteral, null, null, value ? 1 : 0);
    }

    public static Instruction command(String name) {
        return new Instruction(Kind.command, name, null, 0);
    }

    public static Instruction jump(String target) {
        return new Instruction(Kind.jump, target, null, 0);
    }

    public static Instruction branch(String ifTarget, String elseTarget) {
        return new Instruction(Kind.branch, ifTarget, elseTarget, 0);
    }

    private final Kind kind;
    private final String s1;
    private final String s2;
    private final int value;

    private Instruction(Kind kind, String s1, String s2, int value) {
        this.kind = kind;
        this.s1 = s1;
        this.s2 = s2;
        this.value = value;
    }
    ...
}
Run Code Online (Sandbox Code Playgroud)

使用 Kotlin 应该如何完成此操作?

bro*_*oot 5

我们在 Kotlin 中的做法几乎相同,但通过使用伴生对象:

fun main() {
    val instruction = Instruction.literal(42)
}

class Instruction private constructor(...) {
    companion object {
        fun label(name: String) = Instruction(Kind.label, name, null, 0)
        fun literal(value: Int) = Instruction(Kind.intLiteral, null, null, value)
    }

    ...
}
Run Code Online (Sandbox Code Playgroud)

请阅读配套对象以获取更多信息。