Kotlin : error: unresolved reference for a method inside a sealed class
Kotlin : error: unresolved reference for a method inside a sealed class
这个小代码给出 错误:未解决的引用:make :
sealed class Color () {
object Red : Color()
object Blue : Color()
override fun toString(): String =
when (this) {
is Red -> "Red"
is Blue -> "Blue"
else -> "Error"
}
fun make(name: String): Color {
return when (name) {
"Red" -> Red
"Blue" -> Blue
else -> throw Exception ("Error unkown color '$name'")
}
}
}
fun main(args: Array<String>) {
val color = Color.make("Red")
println (color.toString())
}
我尝试了 val color = make("Red") 并得到了同样的错误。为什么 ?我需要做些什么来解决这个问题?
将函数放在伴随对象中:
sealed class Color() {
object Red : Color()
object Blue : Color()
override fun toString(): String = when (this) {
is Red -> "Red"
is Blue -> "Blue"
else -> "Error"
}
companion object {
fun make(name: String): Color = when (name) {
"Red" -> Red
"Blue" -> Blue
else -> throw Exception("Error unkown color '$name'")
}
}
}
这个小代码给出 错误:未解决的引用:make :
sealed class Color () {
object Red : Color()
object Blue : Color()
override fun toString(): String =
when (this) {
is Red -> "Red"
is Blue -> "Blue"
else -> "Error"
}
fun make(name: String): Color {
return when (name) {
"Red" -> Red
"Blue" -> Blue
else -> throw Exception ("Error unkown color '$name'")
}
}
}
fun main(args: Array<String>) {
val color = Color.make("Red")
println (color.toString())
}
我尝试了 val color = make("Red") 并得到了同样的错误。为什么 ?我需要做些什么来解决这个问题?
将函数放在伴随对象中:
sealed class Color() {
object Red : Color()
object Blue : Color()
override fun toString(): String = when (this) {
is Red -> "Red"
is Blue -> "Blue"
else -> "Error"
}
companion object {
fun make(name: String): Color = when (name) {
"Red" -> Red
"Blue" -> Blue
else -> throw Exception("Error unkown color '$name'")
}
}
}