Julia version of state-machine pattern

There is an interesting tweet-thread about a Swift pattern which should have a corresponding Julia version:

Anyone wants to show a Julia version?

3 Likes

Here you go:

struct Park end
struct Drive end
struct Game end

struct Car{State}
    engineSystem::EngineSystem
    infotainmentSystem::InfotainmentSystem
end

function switchToDrive(c::Car{Park})
    activate(c.engineSystem)
    return Car{Drive}(c.engineSystem, c.infotainmentSystem)
end

Passing Car{Drive} would be a detectable MethodError. Note also that this is very far from how actual cars work internally, and using dispatch for this feels very much like a “if all you have is a hammer, everything looks like a nail” kind of situation. It would be much cleaner to use a proper sum-type for this. The julia version also can’t do data hiding the same way Swift can with its private field.

4 Likes