某些东西(可能是 DB?)正在为您提供字符串 "null" for coll_id,或者 (log/info ...) 将 Clojure nil 转换为字符串 "null"。
考虑这段代码:
(ns tst.demo.core
(:use tupelo.core tupelo.test)
(:require
[clojure.string :as str]
))
(defn get-coll-id [^String coll_id]
(println "coll_id: " coll_id)
(if (str/blank? coll_id)
(println :blank)
coll_id))
(dotest
(newline)
(println :v1)
(spyx (get-coll-id nil))
(newline)
(println :v2)
(spyx (get-coll-id (pr-str nil)))
)
带输出:
:v1
coll_id: nil
:blank
(get-coll-id nil) => nil
:v2
coll_id: nil
(get-coll-id (pr-str nil)) => "nil"
无论您做什么,都会打印出值nil 或字符串"nil"。
由于我有一段时间没有使用 Java,我试图强制它生成字符串 "null",但调用 o.toString() 以获得 null 值会创建一个
NullPointerException,所以这不是答案。
更新
正如 amalloy 指出的,String.valueOf() 会将 Java null 转换为字符串 "null":
package demo;
public class Demo {
public static String go() {
Object o = null;
return String.valueOf( o );
}
}
运行时:
(newline)
(spyx :v3 (demo.Demo/go))
结果
:v3 (demo.Demo/go) => "null"
至于您原来的问题,可以使用nil? 函数:
(defn blank-or-nil?
[s]
(or (nil? s)
(str/blank? s)))
(defn get-coll-id [^String coll_id]
(println "coll_id: " coll_id)
(if (blank-or-nil? coll_id)
(println "found blank-or-nil coll_id")
coll_id))
然后在传递 nil 值时打印found blank-or-nil coll_id。但是,如果您传递了字符串 "null" 或字符串 "nil",这可能会造成混淆。
你需要明确哪个值是输入,然后追查源头。
以上代码基于我最喜欢的template project。