不可变(数据)类上的多个构造函数

问题描述 投票:2回答:2

我正在尝试使用多个构造函数实现不可变数据类。我觉得这样的事情应该是可能的:

data class Color(val r: Int, val g: Int, val b: Int) {
   constructor(hex: String) {
        assert(Regex("#[a-fA-F0-6]{6}").matches(hex), { "$hex is not a hex color" } )
        val r = hex.substring(1..2).toInt(16)
        val g = hex.substring(3..4).toInt(16)
        val b = hex.substring(5..6).toInt(16)
        this(r,g,b)
    }
}

当然,它不是:Kotlin期望对主构造函数的调用在顶部声明:

constructor(hex: String): this(r,g,b) {
    assert(Regex("#[a-fA-F0-6]{6}").matches(hex), { "$hex is not a hex color" } )
    val r = hex.substring(1..2).toInt(16)
    val g = hex.substring(3..4).toInt(16)
    val b = hex.substring(5..6).toInt(16)
}

这也没有用,因为调用是在构造函数体之前执行的,并且无法访问局部变量。

我当然可以这样做:

constructor(hex: String): this(hex.substring(1..2).toInt(16),
                               hex.substring(3..4).toInt(16), 
                               hex.substring(5..6).toInt(16)) {
    assert(Regex("#[a-fA-F0-6]{6}").matches(hex), { "$hex is not a hex color" } )
}

但是这将检查断言太晚,并且不能很好地扩展。

我看到接近所需行为的唯一方法是使用辅助函数(无法在Color上定义为非静态函数):

constructor(hex: String): this(hexExtract(hex, 1..2), 
                               hexExtract(hex, 3..4), 
                               hexExtract(hex, 5..6))

这并不是一种非常优雅的模式,所以我猜我在这里缺少一些东西。

在Kotlin中,是否有一种优雅的,惯用的方法可以在不可变的数据类上建立(复杂的)辅助构造函数?

constructor kotlin immutability data-class
2个回答
5
投票

正如@nhaarman所建议的那样,一种方法是使用工厂方法。我经常使用以下内容:

data class Color(val r: Int, val g: Int, val b: Int) {
   companion object {
        fun fromHex(hex: String): Color {
            assert(Regex("#[a-fA-F0-6]{6}").matches(hex), { "$hex is not a hex color" } )
            val r = hex.substring(1..2).toInt(16)
            val g = hex.substring(3..4).toInt(16)
            val b = hex.substring(5..6).toInt(16)
            return Color(r,g,b)
        }
    }
}

然后你可以用Color.fromHex("#abc123")调用它


4
投票

正如here所解释的那样,在伴随对象上使用运算符函数invoke(就像Scala的apply一样),可以实现的不是构造函数,而是一个看起来像构造函数用法的工厂:

companion object {
    operator fun invoke(hex: String) : Color {
        assert(Regex("#[a-fA-F0-6]{6}").matches(hex),
               {"$hex is not a hex color"})
        val r = hex.substring(1..2).toInt(16)
        val g = hex.substring(3..4).toInt(16)
        val b = hex.substring(5..6).toInt(16)
        return Color(r, g, b)
    }
}

现在,Color("#FF00FF")将达到预期的目标。

© www.soinside.com 2019 - 2024. All rights reserved.