javaclojuredata-oriented-designjava-sealed-typeclojure-protocol

Sealed Clojure protocols


I'd like to know if Clojure utilizes the sealed interface/ implementing record pattern in Java, and if so how to define it.

I was thinking along the lines of something like:

(defprotocol 
        ;; protocol definition here 
        :allows
        ;; vector of allowed types) 

Then the REPL should warn you that certain types must be defined.

The java way of doing it would be to define an interface that allows only certain classes, and that way the compiler forces those classes to implement the interface and flatly disallows any other class to implement the interface.

I'd think that this is probably something that is much more plausible in a static language, whereas in a dynamic language this can cause interesting complications.

EDIT

It would be clearer seen in the context of https://www.infoq.com/articles/data-oriented-programming-java/ to understand what I'm looking for.

Basically I think my question could be better phrased as: "How to do controlled ad-hoc polymorphism in Clojure", in the sense of controlled meaning only specific types may extend the protocol. This would then potentially carry the advantages indicated in the link.

Yet still it may be that this is a fundamental difference between dynamic and static programming. So please take the time to confirm or correct my presumptions, and forgive me if I'm asking an irrelevant question.


Solution

  • After a little research, it seems that this is exactly what protocols are NOT all about. Protocols are there to solve the expression problem, and therefore are supposed to be totally unlimited.

    However, Clojure is TC, so it is possible with a map and a private protocol to define a set of functions that produce records and types that utilize the protocol and only the set of types provided.

    If code is reqired for clarification, request in a comment or feel free to write your own implementation.

    Conclusion: sealing protocols as is done in Java, opposes the design intent and is not done. Yet it is perfectly possible to lexically scope a protocol and expose a set of types or records that implement the protocol.