Strings in Kawa (nerd post)
Another random nerd post for the three other people on Earth who will want the answer to this question, concerning Kawa, an implementation of Scheme that compiles to Java bytecode, and allows Java and Scheme code to call each other freely, and which I love more and more each day, but whose documentation could use a few more examples for the newcomer.
To convert from a Java String (java.lang.String) to a Scheme string, all you need to do is:
(gnu.lists.FString:new some-java-string)Kawa represents a Scheme string (which is mutable) as a gnu.lists.FString, not as a java.lang.String (which is immutable), which it uses to represent Scheme symbols. So the Scheme primitive string? will return true for an FString, and not for a java.lang.String. Also, Kawa will turn a scheme string literal, like "hello", into a java.lang.String if used where a java.lang.String is expected, for example as a method argument. Took me a while to figure all this out. So:
> (string? (gnu.lists.FString:new (java.lang.String "hello"))) #t > (string? (gnu.lists.FString:new (java.lang.String:new 'hello))) #tFor example, to obtain the stack trace of a java exception in Kawa (this whole example isn't necessary, but it also illustrates how to use try-catch in Kawa, which a fellow newbie might find useful),
(define (broken-function-that-returns-stack-trace) ;; will throw an exception because 'b is not a list (try-catch (display (car 'b)) ;; catch java.lang.Throwable, ;; binding it to a variable called exception (exception <java.lang.Throwable> ;; and return the exception's stack trace ;; as a scheme string (java-exception-stack-trace exception)))))) (define (java-exception-stack-trace exception) ;; the standard java rigamarole ;; needed to obtain an exception's stack trace (let* ((string-writer (java.io.StringWriter:new)) (print-writer (java.io.PrintWriter:new string-writer))) (java.lang.Throwable:printStackTrace exception print-writer) (java.io.PrintWriter:flush print-writer) ;; here's the String-related bit. convert the java.lang.String ;; from the StringWriter into a gnu.lists.FString (gnu.lists.FString:new (java.lang.Object:toString string-writer))))So:
> (let ((stack-trace (broken-function-that-returns-stack-trace))) (string? stack-trace)) #tAlso, because Kawa represents Scheme symbols as java.lang.Strings (because both are immutable),
> (symbol? (java.lang.String:new "hello")) #t > (java.lang.String:toCharArray 'hello) [h e l l o]Keep on truckin, my partners in Scheme. Wherever you are.