Null from java in casting to other type


#1

javafx.scene.control.ToggleGroup.getSelectedTogger is returning javafx.scene.control.Toggle. It’s ToggleButton.

Let’s cast:

val toggleButton: ToggleButton? = toggleGroup.selectedToggle as ToggleButton

But time to time .selectedToggle() is returning null. And programm crashed with exception:

Exception in thread “JavaFX Application Thread” kotlin.TypeCastException: null cannot be cast to non-null type javafx.scene.control.ToggleButton

Is there a good way to make null checking without temp variable?


#2

You should use a nullable type in the cast: toggleGroup.selectedToggle as ToggleButton?


#3

ok, thanks!