hawkeye
hawkeye

Reputation: 35742

Why doesn't the Clojure Compiler throw an error for an incorrect type hint?

Assumptions:

Suppose I have the following code:

(ns test.core)

(defrecord SquarePeg [width length])
(defrecord RoundHole [radius])

(def square-peg (SquarePeg. 5 50))

(defn insert-peg [^test.core.RoundHole peg]
  (println "insert-peg inserted with: " peg))

(defn -main
  "Insert a square peg in a round hole"
  [& args]
  (insert-peg square-peg))

When I run it I get:

insert-peg inserted with:  #direct_linking_test.core.SquarePeg{:width 5, :length 50}

Now I expect this to have some kind of indication that the type hint was wrong, but it doesn't.

Now I'm taking a look at the Clojure Compiler code - and I'm seeing the following hint handling code:

But I'm not seeing the bit where it handles the type hint failure.

My question is: Why doesn't the Clojure Compiler throw an error for an incorrect type hint?

Upvotes: 5

Views: 214

Answers (1)

gfredericks
gfredericks

Reputation: 1332

Type hints mostly[1] only affect code that would otherwise use reflection -- i.e., interop code.

Since your insert-peg function doesn't do any interop, there's no use for the type hint and it's ignored.

Type errors happen when your type hint caused the clojure compiler to write bytecode for calling the method of one type, but at runtime the instance turns out to be another type.

[1] see exception in Alex's comment below

Upvotes: 4

Related Questions