KStateMachine / kstatemachine

Powerful Kotlin Multiplatform library with clean DSL syntax for creating complex state machines and statecharts driven by Kotlin Coroutines.
https://kstatemachine.github.io/kstatemachine/
Boost Software License 1.0
371 stars 21 forks source link

transitionConditionally get called with mismatching type during unsafe export #111

Open whs opened 21 hours ago

whs commented 21 hours ago

Using

println(machine.exportToMermaid(unsafeCallConditionalLambdas = true))

with a state machine with

           transitionConditionally<SomeEvent> {
                   direction = { .. }
                }

Results in

Exception in thread "main" java.lang.ClassCastException: class ru.nsk.kstatemachine.visitors.export.ExportPlantUmlEvent cannot be cast to class SomeEvent

Workaround is

                transitionConditionally<SomeEvent> {
                    direction = direction@{
                        if(event !is SomeEvent) {
                            return@direction noTransition()
                        }
                        ..
                    }
                }

It does work but the IDE doesn't like it, as it believe that event is always of type SomeEvent.

nsk90 commented 19 hours ago

Hi, this is expected, documented behavior. The Event has to be faked to run "unsafe export".

Unsafe export is development only feature, so you can ignore ide warnings, or try adding some kind of helper method, hiding actual typecheck from ide's lint tool.

nsk90 commented 17 hours ago

I had an idea to add an ability to provide some kind of meta information from user side for runtime export mechanism (like annotation, or additional property). To provide event types, or better instances, so export feature can use those events to perform transition direction calculation. Maybe I will implement this, to improve current behavior. Another option is using PSI tree parcing. I have started working in this direction, but it not so simple, and it still is not a guarantee that all cases could be covered correctly.

whs commented 16 hours ago

My expectation here is that transitionConditionally may be complicated and it might not be possible to retrieve all possible transitions. I think transitionConditionally should not be executed. I turned on the unsafe condition just because I wanted the transitions from transitionOn which use lateinit, but otherwise do not involve complicated procedure.