1

我正在实现一个自定义键盘,我将键 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
  }
}
4

2 回答 2

0

您不能对密封类执行此操作,因为您无法从密封类继承视图。您可以使用抛出异常的 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")
  }
}
于 2020-04-09T01:09:23.233 回答
0

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

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
  }
}
于 2020-04-09T07:22:31.877 回答