# 不变的(数据)类上的多个构造函数[英] Multiple constructors on an immutable (data) class

### 问题描述

```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)
}
}
```

```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" } )
}
```

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

## 推荐答案

```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)
}
}
```

## 其他推荐答案

```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")