How nice to name other JVM languages ​​from clojure?

Sometimes you want to stick solutions in different JVM languages. To do this, you need to name these languages ​​or use java-bit codes in some way. What is the cleanest, safest, most beautiful way to do this in Clojure?

For example, what is the best way to call Scala from Clojure?

(I know the other way is simple. You can generate the class by the gen class, since it is written in Can you mix the JVM languages? Ie: Groovy and Clojure , but this will allow you to use clojure from other languages.)

+7
source share
2 answers

Since Clojure runs on the JVM, you can access any known class that is in your class path from Clojure. Here is an example of a Scala. To simplify class customization and dependency management, use Leiningen to create a project.

lein new clojure-scala 

In the project folder, change project.clj and add the dependency for the Scala language libraries and the scala -src folder to the class path:

 (defproject clj-scala "0.1.0-SNAPSHOT" :description "FIXME: write description" :url "http://example.com/FIXME" :license {:name "Eclipse Public License" :url "http://www.eclipse.org/legal/epl-v10.html"} :dependencies [[org.clojure/clojure "1.3.0"] [org.scala-lang/scala-library "2.7.1"]] :compile-path "scala-src" ) 

Create the scala -src directory, and in this folder create the following Scala class:

 class HelloWorld { def sayHelloToClojure(msg: String) = "Here the echo message from Scala: " concat msg } 

Compile the class with scalac. Now run lein deps to load the dependencies. Launch Clojure REPL by replacing lein. You can import the Scala class, instantiate it, and call the sayHelloToClojure method.

 user=> (import HelloWorld) HelloWorld user=> (.sayHelloToClojure (HelloWorld.) "Hi there") "Here the echo message from Scala: Hi there" 

This is just compatible with how you can use Scala classes and code from Java. This may seem complicated, quote from Frequently Asked Questions - Java Interoperability :

Using the Scala class from Java can be difficult, especially if your Scala class uses advanced features such as generics, polymorphic methods, or abstract types. Since Java does not have such language features, you should know something about the Scala class coding scheme.

+12
source

It's quite easy to invoke other JVM languages ​​from Clojure - all you have to do is use the Java interop syntax .

Examples:

 ;; import Java classes (ns my-ns (:import [some.package ClassOne ClassTwo ClassThree])) ;; call a regular method on an object (.method someObject arg1 arg2) ;; call a constructor (ObjectToConstuct. arg1 arg2) ;; call a static method (Math/floor 2.3) ;; Use a static field (+ 2 Math/PI) 

Basically, using these methods, you can call any other language that creates JVM classes (including Java, Scala, and possibly most other JVM languages)

+5
source

All Articles