Does the Clojure compiler check if records and types implement protocols?
Asked Answered
H

1

1

Is the Clojure compiler meant to check if a record or type that says it instantiates a protocol actually implements the methods listed in it?

I'm trying this out now and so far, it doesn't seem to.

Halfsole answered 15/8, 2015 at 13:46 Comment(3)
i believe that behind the scenes, defprotocol is generating a Java interface. can you share your code?Attendance
@lispHK01 javac enforces that the methods of an interface are implemented, but the vm itself does not. One can easily implement an interface in Clojure without implementing all of its methods.Pyrotechnic
@Pyrotechnic ah interesting! ok good to knowAttendance
T
1

A record can implement a protocol without implementing any of its methods:

(defprotocol Structure
  (weight [this])
  (balanced? [this]))

(defrecord Mobile []
  Structure
  )

... is accepted.

If you try to use a non-existent method:

(balanced? (Mobile.))

;java.lang.AbstractMethodError: user.Mobile.balanced_QMARK_()Ljava/lang/Object;

As usual, type errors are found at run time.

Tyus answered 15/8, 2015 at 15:40 Comment(2)
Do know of any tools that do do a compile-time check on this? I'm not a big fan of static type-checking. But checking that something that claims to implement an interface actually does implement it WOULD be useful.Halfsole
@Halfsole I don't know of any such tool. A follow-up question, perhaps?Tyus

© 2022 - 2024 — McMap. All rights reserved.