在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;
    }
    ...
}

Kotlin 应该怎么做?

推荐答案

我们在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)
    }

    ...
}

请阅读companion objects了解更多信息.

Kotlin相关问答推荐

在Kotlin中将ClosedRange字符串转换为List?<>

调用即发即忘方法--哪个作用域?

找不到有效的 Docker 环境

Rabin-Karp字符串匹配的实现(Rolling hash)

在 Kotlin 中,为什么在 `+` 之前但在 `.` 之前没有换行符?

如何在 Android Jetpack Compose 中的画布上绘制一侧加厚的描边?

Jetpack Compose 中的连续重组

是什么让 Kotlin 中的 String 类能够使用方括号?

Kotlin 使用迭代索引过滤 lambda 数组

如何有效地填充 Gradle Kotlin DSL 中的额外属性?

将 Kotlin 类属性设置器作为函数引用

Kotlin 中的部分类委托

Android Studio 4.0.0 Java 8 库在 D8 和 R8 构建错误中脱糖

片段内的 Kotlin 按钮 onClickListener 事件

如何在 Kotlin 中传递有界通配符类型参数?

有没有办法在数据类构建时转换属性的值?

kotlin RecyclerView分页

接口中的属性不能有支持字段

Kotlin - computed var 属性的用处?

使用 rxbinding 时我应该取消订阅吗?