1

I am implementing a custom keyboard and I am representing the keys 0-9 and the decimal separator as Button objects. Then I have one final key which is the backspace and is being represented as an ImageButton.

When I handle the click events I know that if the user clicked a Button they are adding an element to the text field and if they clicked an ImageButton they are removing the last element from the text field.

Since the keyboard only has two possible type of buttons I wanted to implement this logic with a when block without using an else branch. Is it possible? Looking at the sealed class documentation I don't think it might be but just asking to make sure.

I'd like to do something like this:

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
  }
}
nicoqueijo
  • 872
  • 2
  • 11
  • 28

2 Answers2

0

You can't do this with a sealed class because you can't get the views to inherit from your sealed class. You can use an else branch that throws an exception:

fun handleKeyPress(button: View) {
  when(button) {
    is Button -> // append element to text
    is ImageButton -> // remove last element from text
    else -> error("unsupported view type")
  }
}
Tenfour04
  • 83,111
  • 11
  • 94
  • 154
0

You can wrap the existing types like this:

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
  }
}
Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487