Can you mix the JVM languages? ie: Groovy & Clojure

前端 未结 6 869
难免孤独
难免孤独 2021-02-13 21:27

I understand that you can easily mix groovy&java, clojure&java, whateverJvmLang&java.

Does this also mean I can have clojure and groovy code interact as well

6条回答
  •  渐次进展
    2021-02-13 22:17

    As already mentioned, you can access Clojure classes from Groovy via pre-compilation.

    You can access most popular scripting languages via Java 6's scripting API as well, though Scala and Clojure don't seem to be officially supported. Here are examples from Groovy:

    http://groovy.codehaus.org/JSR-223+access+to+other+JVM+languages

    You can also get access to Clojure's classes from Groovy, e.g. (for Groovy 1.7 snapshot):

    @Grab(group='org.clojure', module='clojure', version='1.0.0')
    import clojure.lang.*
    
    def ss = StringSeq.create('The quick brown fox')
    def done = false
    while (!done) {
      println ss.first()
      ss = ss.next()
      done = !ss
    }
    

    Or interact via creating a new Process (again for Groovy 1.7 snapshot):

    @Grab(group='org.clojure', module='clojure', version='1.0.0')
    import clojure.lang.Script
    
    def src = new File('temp.clj')
    src.text = '''
    (defn factorial [n]
       (if (< n 2)
           1
           (* n (factorial (- n 1)))))
    (println (factorial 4))
    '''
    def path = System.getProperty('user.home') + '/.groovy/grapes/org.clojure/clojure/jars/clojure-1.0.0.jar'
    new AntBuilder().with {
        java(classname:Script.name, classpath:path) {
            arg(value:src.path)
        }
    }
    

    There is also a Clojure plugin for Grails which provides easy access to execute clojure code from any Grails artifact (controllers, taglibs, services etc...):

    http : / / grails.org/plugin/clojure

提交回复
热议问题