【问题标题】:clojure string null check failed with string/blankclojure 字符串空检查失败,字符串/空白
【发布时间】:2021-09-01 05:38:58
【问题描述】:
(defn get-coll-id [^String coll_id]
  (log/info "coll_id: " coll_id)
  (if (string/blank? coll_id)
    (let [collVal (get-coll-val)]
      (log/info "collVal: " collSeqVal)
      (format "C%011.0f" collVal))
    coll_id))

日志显示“coll_id: null”。但是,string/blank 没有检测到 null,因此 collVal 的日志被跳过。检查空字符串的方法是什么?

【问题讨论】:

  • "null" 是一个打印为null 且不为空的值。你检查过你实际拥有的价值吗?
  • 您可以登录(pr-str coll_id) 以获得更明确的报告。 pr-str 以这样一种方式对值进行字符串化,以便 Clojure 阅读器可以重新读取它,因此,实际上(长话短说),字符串被引用而 nil 不是。

标签: clojure


【解决方案1】:

某些东西(可能是 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

【讨论】:

  • (let [^String s nil] (String/valueOf s)) 是您要找的。对于期望字符串但为空的 Java 程序来说,这是一个很好的近似值。我们需要 typehint 因为它已经重载了,如果我们只传递一个空的 nil,Clojure 就会猜到错误的重载。
猜你喜欢
  • 1970-01-01
  • 2018-11-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-04-01
  • 2017-11-25
  • 2010-09-05
  • 1970-01-01
相关资源
最近更新 更多