Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Casting nil in Clojure

Tags:

clojure

I want to call an overloaded Java method from Clojure, and passing in null (or nil in Clojure) has special meaning. How would I ensure that the correct Java method is called if the argument is nil?

e.g. suppose the overloaded Java methods were as follows:

public class Foo {
    public String bar(String s) {
        return (s == null) ? "default" : s;
    }

    public String bar(Integer i) {
        return (i == null) ? "0" : i.toString();
    }
}

I want to yield the value "default", so I want to do the following in my Clojure code:

(.bar (Foo.) (cast String nil))

I've tested this in two slightly different environments and I do not get consistent results. And it appears that casting a nil value in Clojure does not yield the expected type, e.g. --

(type (cast String nil))
; => nil
like image 1000
pestrella Avatar asked Feb 07 '26 11:02

pestrella


1 Answers

cast doesn't do what you think it just ensures the second argument is of the specified class and returns it (the 2nd argument, not the class) or throws an exception.

You need to add a type hint but you can't add it directly to nil:

=> (String. nil)
CompilerException java.lang.IllegalArgumentException: More than one matching method found: java.lang.String

Here I have an exception because nil matches too many overloads and the compiler doesn't know which to pick.

=> (let [^String cnil nil] (String. cnil))
NullPointerException   java.lang.String.<init> (String.java:152)

Here I have an exception but from the constructor: the type hint allowed the compiler to select the proper overload (which overload complains about being passed a nil...).

like image 161
cgrand Avatar answered Feb 09 '26 07:02

cgrand



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!