【问题标题】:Sealed class with existing classes?密封类与现有类?
【发布时间】:2020-04-09 00:47:50
【问题描述】:

我正在实现一个自定义键盘,我将键 0-9 和小数点分隔符表示为 Button 对象。然后我有一个最后一个键,它是退格键,它被表示为一个 ImageButton。

当我处理点击事件时,我知道如果用户点击按钮,他们将向文本字段添加一个元素,如果他们点击 ImageButton,他们将从文本字段中删除最后一个元素。

由于键盘只有两种可能的按钮类型,我想用 when 块实现这个逻辑,而不使用 else 分支。是否可以?查看密封的课程文档,我认为这可能不是,只是要求确保。

我想做这样的事情:

sealed class KeyboardButton {
  class Button
  class ImageButton
}

fun handleKeyPress(button: View) {
  when(button) {
    is KeyboardButton.Button -> // append element to text
    is KeyboardButton.ImageButton -> // remove last element from text
  }
}

【问题讨论】:

    标签: kotlin sealed-class


    【解决方案1】:

    您不能对密封类执行此操作,因为您无法从密封类继承视图。您可以使用抛出异常的 else 分支:

    fun handleKeyPress(button: View) {
      when(button) {
        is Button -> // append element to text
        is ImageButton -> // remove last element from text
        else -> error("unsupported view type")
      }
    }
    

    【讨论】:

      【解决方案2】:

      您可以像这样包装现有类型:

      sealed class KeyboardButton {
        class KButton(val x: Button)
        class KImageButton(val x: ImageButton)
      }
      
      fun handleKeyPress(button: KeyboardButton) {
        when(button) {
          is KeyboardButton.KButton -> // use button.x to access the underlying Button
          is KeyboardButton.KImageButton -> // similarly use button.x
        }
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2021-11-05
        • 1970-01-01
        • 1970-01-01
        • 2021-12-15
        • 1970-01-01
        • 1970-01-01
        • 2011-03-03
        • 1970-01-01
        相关资源
        最近更新 更多