YS / Java Interoperability
We know that YS is made from Clojure and the Clojure is made from Java. Clojure code is interoperable with Java code.
So is YS interoperable with Java?
Yes, YS is can call Java methods on its objects.
Let's see how to do it.
Calling Java Methods🔗
Let's start with a simple example.
We can turn an integer into a string in several ways with YS.
$ ys -pe 'str: 42'
"42"
$ ys -pe 'str(42)'
"42"
$ ys -pe '42.str()'
"42"
$ ys -pe '42:str'
"42"
What is 42 really?
$ ys -pe '42:type'
java.lang.Long
Interesting.
It's actually a java.lang.Long
instance object!
It would be cool if we could call the Java Long
instance methods on it.
It turns out we can!
Let's look here
to see what methods are available.
We can see that toString
is available.
Let's try it!
$ ys -pe '42.~toString()'
"42"
Very nice.
Java Interop Syntax for Instance Methods🔗
In YS, Java instance methods require a ~
prefix.
After that, most of the YS expression forms should work the same as standard YS function calls:
$ ys -pe '~toString: 42'
"42"
$ ys -pe '42.~toString()'
"42"
$ ys -pe '42:~toString'
"42"
Java Interop Syntax for Static Methods🔗
YS also supports calling static methods on Java classes.
If you looked carefully at the java.lang.Long
documentation, you may have seen
the there is also a static method called toString
.
We can call it like this:
$ ys -pe 'Long/toString: 42'
"42"
$ ys -pe 'Long/toString(42)'
"42"
$ ys -pe '42:Long/toString'
"42"
In YS, Java static methods are prefixed with their class name and a /
.
Note: Long
is the short name for java.lang.Long
.
Going Further🔗
I've only shown you the basics of Java interop in YS.
Hopefully I've shown you enough for you to figure out how to call more interesting Java methods on YS objects.
Java interop is a fairly new addition to YS.
Let me know how it works out for you in the comments below!