【问题标题】:Kotlin : error: unresolved reference for a method inside a sealed classKotlin:错误:密封类中方法的未解析引用
【发布时间】:2020-02-28 02:07:31
【问题描述】:

这个小代码给出了错误:未解决的参考: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") 并得到了同样的错误。为什么 ?我必须做些什么来解决这个问题?

【问题讨论】:

  • 你的make 是一个实例方法,即你需要一个Color 的实例来调用它:就像Color().make("red") 一样,这是因为Color 没有参数构造函数。如果您希望像在示例中那样调用它,可以将 make 放在伴随对象中。

标签: class kotlin sealed


【解决方案1】:

将函数放在伴随对象中:

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

Kotlin Playground

【讨论】:

  • 我这样做了,在主函数中得到了同样的错误:val color = make("Red") error: unresolved reference: make
  • @EmileAchadde 你可能做错了什么。它对我来说非常好。确保你使用val color = Color.make("Red")
  • 你说得对,我没有在 val color = Color.make("Red") 中指定颜色,效果很好!
猜你喜欢
  • 1970-01-01
  • 2018-06-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多