Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I check if a variable implements an interface in clojure?

Tags:

clojure

So I have defined say a keyword:

(def a :hello)

how do I check that it implements the IFn interface?

like image 783
zcaudate Avatar asked Aug 29 '12 03:08

zcaudate


People also ask

How do you know if a class implements an interface?

A class implements an interface if it declares the interface in its implements clause, and provides method bodies for all of the interface's methods. So one way to define an abstract data type in Java is as an interface, with its implementation as a class implementing that interface.

How do you check if an object is an instance of an interface?

The java “instanceof” operator is used to test whether the object is an instance of the specified type (class or subclass or interface). It is also known as type comparison operator because it compares the instance with type. It returns either true or false.

Which keyword validates whether a class implements an interface?

To declare a class that implements an interface, include an implements keyword in the class declaration.

Can a variable be of type interface?

Interface types act like class types. You can declare variables to be of an interface type, you can declare arguments of methods to accept interface types, and you can even specify that the return type of a method is an interface type.


1 Answers

For the general case, you can use the instance? predicate:

(instance? <class-or-interface> <object>)

Quoting the documentation:

(instance? c x) evaluates x and tests if it is an instance of the class c. Returns true or false.

For example:

(instance? java.lang.String "test")
> true

(instance? java.io.Serializable "test")
> true

For the code in the question, do something like this:

(instance? package.of.IFn a)

Or, as has been pointed out in the comments, for the very specific case of asking if a is an instance of IFn this will work:

(ifn? a)
like image 80
Óscar López Avatar answered Sep 30 '22 19:09

Óscar López