liveBook · Manning

Instance?

As explained in Clojure: The Essential Reference

instance? is a Clojure predicate that tests whether an object is an instance of a specified Java class or interface according to Java inheritance rules.

instance? tests whether a value is an instance of a specified Java class or interface, returning a boolean according to Java inheritance rules. section 15.2

Use instance? when the relevant question is whether a runtime value conforms to a Java type:

  • A bigint is an instance of java.lang.Number. section 15.2
  • An integer is an instance of java.lang.Comparable. section 15.2
  • clojure.test accepts instance? as a predicate for assertions that are not equality checks. section 22.9

Checking classes and interfaces

(instance? java.lang.Number (bigint 1)) ;; true (instance? java.lang.Comparable 1) ;; true section 15.2

Using instance? in tests

(is (instance? Double (sqrt nil))) ;; Error: java.lang.NullPointerException section 22.9

How Clojure: The Essential Reference covers it

How deep it goes
Defines the predicate and demonstrates class and interface checks, without descending into implementation internals.
Examples
Uses bigint with Number, integer with Comparable, and an instance? assertion involving sqrt.
What you can do after
Apply it via Clojure expressions or clojure.test assertions to check runtime Java type membership.
How it connects
Connects instance? with Java classes, interfaces, type, class, and clojure.test assertion predicates.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Clojure: The Essential Reference. The section links point to the parts of the book it draws on.