haw*_*eye 5 compiler-errors clojure type-hinting compiler-optimization
假设:
假设我有以下代码:
(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))
Run Code Online (Sandbox Code Playgroud)
当我运行它时,我得到:
insert-peg inserted with: #direct_linking_test.core.SquarePeg{:width 5, :length 50}
Run Code Online (Sandbox Code Playgroud)
现在我希望这能表明类型提示是错误的,但事实并非如此。
现在我正在查看Clojure 编译器代码- 我看到以下提示处理代码:
但我没有看到它处理类型提示失败的部分。
我的问题是:为什么 Clojure 编译器不会因类型提示不正确而抛出错误?
类型提示大多[1]只影响原本使用反射的代码——即互操作代码。
由于您的insert-peg函数不执行任何互操作,因此类型提示没有用处,并且会被忽略。
当类型提示导致 clojure 编译器编写字节码来调用一种类型的方法时,就会发生类型错误,但在运行时该实例却是另一种类型。
[1] 请参阅下面 Alex 评论中的异常