Why do we need other JVM languages

前端 未结 17 1549
滥情空心
滥情空心 2021-02-02 10:30

I see here that there are a load of languages aside from Java that run on the JVM. I\'m a bit confused about the whole concept of other languages running in the JVM. So:

17条回答
  •  南方客
    南方客 (楼主)
    2021-02-02 11:30

    To address your three questions separately:

    What is the advantage in having other languages for the JVM?

    There are two factors here. (1) Why have a language other than Java for the JVM, and (2) why have another language run on the JVM, instead of a different runtime?

    1. Other languages can satisfy other needs. For example, Java has no built-in support for closures, a feature that is often very useful.
    2. A language that runs on the JVM is bytecode compatible with any other language that runs on the JVM, meaning that code written in one language can interact with a library written in another language.

    What is required (in high level terms) to write a language/compiler for the JVM?

    The JVM reads bytecode (.class) files to obtain the instructions it needs to perform. Thus any language that is to be run on the JVM needs to be compiled to bytecode adhering to the Sun specification. This process is similar to compiling to native code, except that instead of compiling to instructions understood by the CPU, the code is compiled to instructions that are interpreted by the JVM.

    How do you write/compile/run code in a language (other than Java) in the JVM?

    Very much in the same way you write/compile/run code in Java. To get your feet wet, I'd recommend looking at Scala, which runs flawlessly on the JVM.

    Answering your follow up questions:

    How would an app written in, say, JPython, interact with a Java app?

    This depends on the implementation's choice of bridging the language gap. In your example, Jython project has a straightforward means of doing this (see here):

    from java.net import URL
    u = URL('http://jython.org')
    

    Also, can that JPython application use any of the JDK functions/objects?

    Yes, see above.

    What if it was Jaskell code, would the fact that it is a functional language not make it incompatible with the JDK?

    No. Scala (link above) for example implements functional features while maintaining compatibility with Java. For example:

    object Timer {
      def oncePerSecond(callback: () => unit) {
        while (true) { callback(); Thread sleep 1000 }
      }
      def timeFlies() {
        println("time flies like an arrow...")
      }
      def main(args: Array[String]) {
        oncePerSecond(timeFlies)
      }
    }
    

提交回复
热议问题