【发布时间】: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