Java interop cookbook
Five things come up again and again where your code meets Java: a result that may be null, a checked exception, a collection, a callback, and an overloaded method. Each recipe shows the program the compiler rejects, what it says, and the version that works. The docs check runs every program on this page and compares what it prints with the block under it.
If you haven't called Java from Sprig yet, start with the Java chapter of the book. The rules in full are in the JVM interop reference.
One habit helps with all five: look the signature up instead of guessing it.
sprig api java.util.ArrayList --member sortThis prints each overload as Java declares it and as Sprig sees it. Add --json for the machine-readable form (sprigParameterTypes, sprigReturnType, checkedExceptions, interopReasonCodes). For a library outside the JDK, run it in the resolved project or pass --classpath.
A result that may be null
HashMap.get returns nothing when the key is missing, so Sprig types its result String? and won't let you use it as a String:
import java.util.HashMap as HashMap
let names = HashMap[String, String]()
let name = names.get("missing")
print(name.length())SPR-TYPE-NULLABLE [TYPE] main.spr:4:12: Cannot access 'length' on a value that may be null (receiver type String?)
hint: Bind the receiver to a let and check it with 'if value != null:' before using 'length'.Keep the result in a let and say what happens in both cases:
import java.util.HashMap as HashMap
let names = HashMap[String, String]()
let name = names.get("missing")
if name != null:
print(name.length())
else:
print("missing")missing- Only a
letnarrows. If the value lives in avar, copy it into aletand check the copy. - A Java reference result is nullable unless the library annotates it as non-null.
toString()is always aString. - When the value really is optional,
or_elsefrom@std/nulls.sprgives it a fallback. Don't add a default just to make the error go away: when the data is required, a missing value is a failure you should report.
A checked exception
URI(text) declares URISyntaxException. A named function has to catch it or declare it:
import java.net.URI as URI
import java.net.URISyntaxException as URISyntaxException
func parse_uri(text: String) -> URI:
return URI(text)SPR-FLOW-THROWS [FLOW] main.spr:4:12: Call may throw URISyntaxException; declare 'throws URISyntaxException' or handle it with try/catchThe next program does both. parse_uri declares the Java exception and passes it on, so a caller can still catch it by its type. parse_for_callback catches it and throws an Error with a message of its own:
import java.net.URI as URI
import java.net.URISyntaxException as URISyntax
func parse_uri(text: String) -> URI throws URISyntax:
return URI(text)
func parse_for_callback(text: String) -> URI throws Error:
try:
return parse_uri(text)
catch problem: URISyntax:
throw Error("invalid URI: " + text)
try:
print(parse_uri("https://example.com"))
catch problem: URISyntax:
print("invalid URI")
try:
parse_for_callback("::bad")
catch problem: Error:
print(problem.message)https://example.com
invalid URI: ::bad- Translate to
Errorwhen the function will be passed around as a value. A function type can end withthrows Errorand nothing else, so a checked Java exception never crosses one. Error(message)keeps the message and not the Java exception behind it. If callers need the original, declare it and let it propagate.- A caught Java exception's
messageis aString?, becausegetMessage()may returnnull.problem.toString()is always aString.
A collection
A Sprig list isn't a java.util.List, even when both hold strings:
import java.util.Collections as Collections
Collections.sort(["b", "a"])SPR-JVM-MEMBER [JVM] main.spr:2:1: Java class Collections has no method 'sort' matching 1 argument(s)
hint: Run sprig api java.util.Collections --member sort to see the signatures this call can match.Copy the list into a Java one with @std/jvm.spr, let Java work on the copy, then take a Sprig snapshot of the result:
import "@std/jvm.spr" as jvm
import java.util.Collections as Collections
let original: List[String] = ["b", "a"]
let copy = jvm.list_copy[String](original)
Collections.sort(copy)
let snapshot = jvm.list_snapshot[String](copy)
copy.add("c")
print(original)
print(snapshot)
print(copy.size())[b, a]
[a, b]
3list_copygives you a separate, mutableArrayList. Sorting it leavesoriginalas it was, which is the first line.list_snapshotgives you a read-only SprigListof what the Java list holds at that moment. Theadd("c")afterwards makescopythree long and doesn't touchsnapshot.- Maps work the same way with
map_copyandmap_snapshot. - A snapshot isn't a live view, and it doesn't copy the objects inside. A
nullin the Java collection makes it throwError.
A callback
A Java parameter whose type is a functional interface (Runnable, Comparator, Consumer and so on) takes a Sprig fn value. It can't take one that may throw Error, because Java has no way to see that:
import java.lang.Thread as Thread
func fail() -> Unit throws Error:
throw Error("failed")
let thread = Thread(fn() => fail())SPR-TYPE-CALLABLE-THROWS [TYPE] main.spr:4:21: A function value that may throw Error cannot be passed to Java parameter 1 of Thread; Java cannot see the throws clause (expected fn() -> Unit, actual fn() -> Unit throws Error)
hint: Handle the error inside a named function and pass a lambda that calls it.Decide in a named function what a failure means, and pass a lambda that calls it:
import java.util.ArrayList as ArrayList
import java.lang.Thread as Thread
func work() -> Unit throws Error:
throw Error("failed")
func run_callback() -> Unit:
try:
work()
catch problem: Error:
print(problem.message)
let names = ArrayList[String]()
names.add("bb")
names.add("a")
names.sort(fn(a: String, b: String) => a.compareTo(b))
print(names)
let thread = Thread(fn() => run_callback())
thread.start()
thread.join()[a, bb]
failedrun_callbackprints the message. Your program might log it, count it or keep it for later; what matters is that you made the decision and wrote it down.- For a comparator, write the parameter types and return
a.compareTo(b). Its result is theInt32thatComparatorexpects. - An interface with several abstract methods, or a callback that keeps state, is a class with
conform. See conformance.
An overloaded method or constructor
StringBuilder has four constructors, and none of them takes a Float:
import java.lang.StringBuilder as StringBuilder
let builder = StringBuilder(1.5)SPR-JVM-MEMBER [JVM] main.spr:2:15: No constructor of StringBuilder matches 1 argument(s)
hint: Run sprig api java.lang.StringBuilder --member '<init>' to see the signatures this call can match.Run the command from the hint, pick the overload you mean, and give the argument that type:
sprig api java.lang.StringBuilder --member '<init>'
sprig api java.lang.Math --member maximport java.lang.StringBuilder as StringBuilder
import java.lang.Math as Math
let capacity: Int32 = 16
let builder = StringBuilder(capacity)
builder.append("rows=")
builder.append(3)
print(builder.toString())
let small: Int32 = 2
let large: Int32 = 3
print(Math.max(small, large))rows=3
3- An
Int32value selects theintoverload. A plainIntprefers an exactlongoverload when there is one; otherwise it narrows toint, with a range check at run time. - Java calls take positional arguments only.
- Type arguments in brackets, as in
Collections.emptyList[String](), settle a generic method's type parameter. They don't choose between overloads. SPR-JVM-AMBIGUOUSmeans two overloads fit equally well. Look at the candidates the diagnostic lists and change an argument's type until one fits; the compiler won't pick for you.
