Polyglot JVMA Quick Tour of JVM Languages
@ArturoHerrerohttp://arturoherrero.com
Working at OSOCOSmall but outstanding software development shop           Groovy and Grails hackers               on EC2 c...
Java Platform    _____________________________________  /                                     /||-------------------------...
> 200 languages on JVMJavaFX           Ceylon      Gosu         Groovy                            ClojureRhino            ...
The Da Vinci Machine ProjectWe are extending the JVM with first-classarchitectural support for languages other thanJava, e...
The Da Vinci Machine ProjectJSR 223: Scripting for the Java PlatformJSR 292: Supporting Dynamically Typed         Language...
Polyglot Programming
Ola Bini Programming Pyramid                   /                /                / DSL               /------             /...
Ola Bini Programming PyramidDomain-Specific (DSL, web templating) Specific part of the applicationDynamic (Groovy, Clojure...
Civilization advances by extending thenumber of important operations which wecan perform without thinking about them.     ...
New languagesNew ways to think about problems
Language Clasification                functional                    |                    |                    |           ...
StackOverflow Questions|      8,268|       __|      | ||      | |       3,847|      | |        __       2,762|      | |   ...
| |                                     | |StackOverflow Questions              | |                                     | ...
Indeed Job Trends|      0,06|       __|      | ||      | |       0,03|      | |        __|      | |       | |       0,01| ...
| |                                     | |Indeed Job Trends                    | |                                     | ...
All of them●   Everything is an object●   Operator overloading●   Native syntax for collection classes●   Regular expressi...
Groovy●   Dynamic Language●   Object-Oriented●   Designed for the JVM●   Inspired by Python, Ruby and Smalltalk●   Good in...
Hello Groovy    println Hello World
ScriptingTypically dynamic languages  No need to define variable before you use  them. Many type conversionMost scripting ...
Groovy Beansclass Person {    String name    Integer age}def person = new Person(name: John, age: 30)def name = person.nam...
Static vs. DynamicStatic typing A programming language is said to use static typing when type checking is performed during...
Optional Typing    Integer object    object = 4    object = noun    ERROR    org.codehaus.groovy.runtime.    typehandling....
Optional Typing      def object      object   =   4      object   =   noun      object   =   true      object   =   [1, no...
Java → Groovyimport java.util.List;import java.util.ArrayList;public class Filter {    public static void main(String[] ar...
Java → Groovy...      private List filterLongerThan(List strings, int length) {          List result = new ArrayList();   ...
Java → Groovydef names = ["Ted", "Fred"] << "Jed" << "Ned"println namesdef shortNames = names.findAll { it.size() <= 3 }pr...
Static language      interface Animal {          def quack()      }      class Duck implements Animal {          def quack...
Polymorphism      Animal animal      animal = new Duck()      animal.quack()      ===> I am a Duck      animal = new Frog(...
Dynamic language     class Duck {         def quack() {             println "I am a Duck"         }     }     class Frog {...
Duck typing       def animal       animal = new Duck()       animal.quack()       ===> I am a Duck       animal = new Frog...
Dynamic Method Call   class Dog {       def bark() { println "woof!" }       def jump() { println "boing!" }   }   def doA...
Dynamic Method Call     someObject."$methodName"()     def rex = new Dog()     doAction(rex, "bark")     ===> woof!     do...
MetaprogrammingPrograms that write or manipulateother programsCompile time  ● Groovy ASTRuntime  ● Hook into method dispac...
AST Transformations    @Singleton    class Singleton {}    @EqualsAndHashCode    class Person {        String name, lastNa...
Method Missing   class Dog {       def bark() { println "woof!" }       def jump() { println "boing!" }   }   def rex = ne...
Method Missing class Dog {     def bark() { println "woof!" }     def jump() { println "boing!" }     def methodMissing(St...
Adding methods to aclass at runtime   4.toRoman()   ERROR   groovy.lang.MissingMethodException
Adding methods to aclass at runtime   SomeObject.metaClass.newMethod = { ->     // do something   }   Integer.metaClass.to...
Scala●   Object-Oriented and Functional Language●   Stronger type system●   Designed for the JVM●   Concurrency: Actors●  ...
Hello Scala  object HelloWorld {      def main(args: Array[String]) {          println("Hello World")      }  }
Scala Types     scala> 1 + 1     res1: Int = 2     scala> (1).+(1)     res2: Int = 2     scala> "a" + "b"     res3: java.l...
Classes  class Person(name: String, age: Int)  val person = new Person("John", 30)
Objects   object Singleton {       def start = println("Start")   }   scala> Singleton.start   Start
Anatomy of a Function  def max (x: Int, y: Int): Int = {      if (x > y)          x      else          y  }
Type Inference // Java Map<String, List<Integer>> map =     new HashMap<String, List<Integer>>() // Java 7 Map<String, Lis...
Variable Declaration  var mutable = "I am mutable"  mutable = "Touch me, change me..."  val immutable = "I am not mutable"...
ImmutabilitySimple  Immutable objects can only be in exactly  one state, the state in which it was createdAlways consisten...
Imperative vs. DeclarativeImperative: how to achieve our goal Take the next customer from a list. If the customer lives in...
Mutability   val listOneToTen: List[Int] = {       var list: List[Int] = List()       var i: Int = 1       while (i <= 10)...
Immutability def listToTen(i: Int): List[Int] = {     if (i <= 10)         i :: listToTen(i + 1)     else         Nil } va...
Range  scala> println(listOneToTen)  List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)          (1 to 10) toList
Mixin Traits class Person(val name: String) trait Power {     def fly() = println("Fly") } class SuperHero(override val na...
Pattern Matchingdef determineType(x:Any) = x match {    case s: String => println("String")    case l: List[_] => println(...
Clojure●   Clojure is LISP●   Dynamic language●   Designed for the JVM●   Code is data●   Powerful macros●   Good interope...
Why Functional Programming?    Referential transparencyλ    Unit testingλ    Debbugingλ    Parallelizationλ    Modularity ...
Hello Clojure    (println "Hello World")
Prefix notation        (+ 1 2)        => 3        (+ 1 2 3 4 5)        => 15        (< 1 2 3 4 5)        => true
Anatomy of a Function(defn biggest  "Find the maximum of two numbers"  [x y]  (if (> x y) x y))
Anatomy of a Function(def biggest  "Find the maximum of two numbers"  (fn [x y]    (if (> x y) x y)))
Function Composition    (defn square [x] (* x x))    (square 21)    => 441    (square (+ 2 5))    => 49
Function Composition  (defn sum-of-squares [x y]      (+ (square x) (square y)))  (sum-of-squares 3 4)  => 25
Immutability (def my-list (1 2 3)) +---+      +---+      +---+ | 1 | ---> | 2 | ---> | 3 | +---+      +---+      +---+ (de...
Lazy EvaluationOnly does as much work as necessary Delays the evaluation of the expression until its neededCPU efficient  ...
Infinite Sequences  (take 3 (repeat "Hello"))  => ("Hello" "Hello" "Hello")  (take 5 (cycle [1 2 3]))  => (1 2 3 1 2)  (ta...
Clojure STM (def my-account (ref 1000.)) (def other-account (ref 5000.)) (defn transfer     [from to amount]     (dosync  ...
Thank you!@ArturoHerrero
Polyglot JVM
Polyglot JVM
Upcoming SlideShare
Loading in...5
×

Polyglot JVM

11,269

Published on

My talk about Polyglot JVM.
A Quick Tour of Java Virtual Machine Languages: Java, Groovy, Scala, Clojure.

Codemotion
http://codemotion.es/
24.03.2012

Published in: Technology

Polyglot JVM

  1. 1. Polyglot JVMA Quick Tour of JVM Languages
  2. 2. @ArturoHerrerohttp://arturoherrero.com
  3. 3. Working at OSOCOSmall but outstanding software development shop Groovy and Grails hackers on EC2 cloud nine TDD mantra singers Quality preachers
  4. 4. Java Platform _____________________________________ / /||------------------------------------| || Java Programming Language | ||------------------------------------| || Libraries & APIS | ||------------------------------------| || Java Virtual Machine | ||------------------------------------|/
  5. 5. > 200 languages on JVMJavaFX Ceylon Gosu Groovy ClojureRhino Java Mirah Scala JRubyXtend JPython Fantom Oxygene Kotlin
  6. 6. The Da Vinci Machine ProjectWe are extending the JVM with first-classarchitectural support for languages other thanJava, especially dynamic languages. This projectwill prototype a number of extensions to the JVM, sothat it can run non-Java languages efficiently, with aperformance level comparable to that of Java itself.
  7. 7. The Da Vinci Machine ProjectJSR 223: Scripting for the Java PlatformJSR 292: Supporting Dynamically Typed Languages on the Java PlatformNew JDK 7 instruction: invokedynamic
  8. 8. Polyglot Programming
  9. 9. Ola Bini Programming Pyramid / / / DSL /------ / Dynamic / /------------ / Stable / /------------------
  10. 10. Ola Bini Programming PyramidDomain-Specific (DSL, web templating) Specific part of the applicationDynamic (Groovy, Clojure) Rapid, productive, flexible development or funcionalityStable (Java, Scala) Core funcionality, stable, well-tested, performance
  11. 11. Civilization advances by extending thenumber of important operations which wecan perform without thinking about them. Alfred North Whitehead
  12. 12. New languagesNew ways to think about problems
  13. 13. Language Clasification functional | | | | -----------------+-----------------static | dynamic | | | not functional
  14. 14. StackOverflow Questions| 8,268| __| | || | | 3,847| | | __ 2,762| | | | | __| | | | | | || | | | | | ||------+--+------+--+------+--+------
  15. 15. | | | |StackOverflow Questions | | | | 222,722 | || 8,268 | || __ | || | | | || | | 3,847 | || | | __ 2,762 | || | | | | __ | || | | | | | | | || | | | | | | | ||------+--+------+--+------+--+------+--+-
  16. 16. Indeed Job Trends| 0,06| __| | || | | 0,03| | | __| | | | | 0,01| | | | | __| | | | | | ||------+--+------+--+------+--+------
  17. 17. | | | |Indeed Job Trends | | | | 3,40 | || 0,06 | || __ | || | | | || | | 0,03 | || | | __ | || | | | | 0,01 | || | | | | __ | || | | | | | | | ||------+--+------+--+------+--+------+--+-
  18. 18. All of them● Everything is an object● Operator overloading● Native syntax for collection classes● Regular expressions as first class citizens● Closures● Facilities to build DSLs
  19. 19. Groovy● Dynamic Language● Object-Oriented● Designed for the JVM● Inspired by Python, Ruby and Smalltalk● Good integration with Java● 2003
  20. 20. Hello Groovy println Hello World
  21. 21. ScriptingTypically dynamic languages No need to define variable before you use them. Many type conversionMost scripting languages are interpreted Perform the script compilation and execution within the same processFast results for small jobs Write application faster Execute commands repeatedly
  22. 22. Groovy Beansclass Person { String name Integer age}def person = new Person(name: John, age: 30)def name = person.nameperson.age = 35
  23. 23. Static vs. DynamicStatic typing A programming language is said to use static typing when type checking is performed during compile time as opposed to runtimeDynamic typing A programming language is said to be dynamically typed when the majority of its type checking is performed at runtime as opposed to at compile time
  24. 24. Optional Typing Integer object object = 4 object = noun ERROR org.codehaus.groovy.runtime. typehandling.GroovyCastException
  25. 25. Optional Typing def object object = 4 object = noun object = true object = [1, noun, true] object = [1: noun]
  26. 26. Java → Groovyimport java.util.List;import java.util.ArrayList;public class Filter { public static void main(String[] args) { List names = new ArrayList(); names.add("Ted"); names.add("Fred"); names.add("Jed"); names.add("Ned"); System.out.println(names); Filter filter = new Filter(); List shortNames = filter.filterLongerThan(names, 3); System.out.println(shortNames.size()); for (String item : shortNames) { System.out.println(item); } }...
  27. 27. Java → Groovy... private List filterLongerThan(List strings, int length) { List result = new ArrayList(); for (String item : strings) { if (item.length() <= length) { result.add(item); } } return result; }}
  28. 28. Java → Groovydef names = ["Ted", "Fred"] << "Jed" << "Ned"println namesdef shortNames = names.findAll { it.size() <= 3 }println shortNames.size()shortNames.each { name -> println name }
  29. 29. Static language interface Animal { def quack() } class Duck implements Animal { def quack() { println "I am a Duck" } } class Frog implements Animal { def quack() { println "I am a Frog" } }
  30. 30. Polymorphism Animal animal animal = new Duck() animal.quack() ===> I am a Duck animal = new Frog() animal.quack() ===> I am a Frog
  31. 31. Dynamic language class Duck { def quack() { println "I am a Duck" } } class Frog { def quack() { println "I am a Frog" } }
  32. 32. Duck typing def animal animal = new Duck() animal.quack() ===> I am a Duck animal = new Frog() animal.quack() ===> I am a Frog
  33. 33. Dynamic Method Call class Dog { def bark() { println "woof!" } def jump() { println "boing!" } } def doAction(animal, action) { animal."$action"() }
  34. 34. Dynamic Method Call someObject."$methodName"() def rex = new Dog() doAction(rex, "bark") ===> woof! doAction(rex, "jump") ===> boing!
  35. 35. MetaprogrammingPrograms that write or manipulateother programsCompile time ● Groovy ASTRuntime ● Hook into method dispaching ● Dynamically create methods/properties ● Dynamic execution of expressions
  36. 36. AST Transformations @Singleton class Singleton {} @EqualsAndHashCode class Person { String name, lastName } @Immutable class Coordinates { Double latitude, longitude }
  37. 37. Method Missing class Dog { def bark() { println "woof!" } def jump() { println "boing!" } } def rex = new Dog() rex.sit() ERROR groovy.lang.MissingMethodException
  38. 38. Method Missing class Dog { def bark() { println "woof!" } def jump() { println "boing!" } def methodMissing(String name, args) { println "sit!" } } rex.sit() ===> sit!
  39. 39. Adding methods to aclass at runtime 4.toRoman() ERROR groovy.lang.MissingMethodException
  40. 40. Adding methods to aclass at runtime SomeObject.metaClass.newMethod = { -> // do something } Integer.metaClass.toRoman = { -> println IV } 4.toRoman() ===> IV
  41. 41. Scala● Object-Oriented and Functional Language● Stronger type system● Designed for the JVM● Concurrency: Actors● Many advanced language features● As fast as Java● 2003
  42. 42. Hello Scala object HelloWorld { def main(args: Array[String]) { println("Hello World") } }
  43. 43. Scala Types scala> 1 + 1 res1: Int = 2 scala> (1).+(1) res2: Int = 2 scala> "a" + "b" res3: java.lang.String = ab scala> "abc".size res4: Int = 3
  44. 44. Classes class Person(name: String, age: Int) val person = new Person("John", 30)
  45. 45. Objects object Singleton { def start = println("Start") } scala> Singleton.start Start
  46. 46. Anatomy of a Function def max (x: Int, y: Int): Int = { if (x > y) x else y }
  47. 47. Type Inference // Java Map<String, List<Integer>> map = new HashMap<String, List<Integer>>() // Java 7 Map<String, List<Integer>> map = new HashMap<>() // Scala val map = new HashMap[String, List[Int]]
  48. 48. Variable Declaration var mutable = "I am mutable" mutable = "Touch me, change me..." val immutable = "I am not mutable" immutable = "Cant touch this" error: reassignment to val
  49. 49. ImmutabilitySimple Immutable objects can only be in exactly one state, the state in which it was createdAlways consistent Less prone to errors and more secureImmutable objects can be shared freely Freedom to cacheInherently thread-safe
  50. 50. Imperative vs. DeclarativeImperative: how to achieve our goal Take the next customer from a list. If the customer lives in Spain, show their details. If there are more customers in the list, go to the beginningDeclarative: what we want to achieve Show customer details of every customer living in Spain
  51. 51. Mutability val listOneToTen: List[Int] = { var list: List[Int] = List() var i: Int = 1 while (i <= 10) { list :+= i i += 1 } list }
  52. 52. Immutability def listToTen(i: Int): List[Int] = { if (i <= 10) i :: listToTen(i + 1) else Nil } val listOneToTen = listToTen(1)
  53. 53. Range scala> println(listOneToTen) List(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) (1 to 10) toList
  54. 54. Mixin Traits class Person(val name: String) trait Power { def fly() = println("Fly") } class SuperHero(override val name:String) extends Person(name) with Power val superMan = new SuperHero("SuperMan") scala> superMan.fly Fly
  55. 55. Pattern Matchingdef determineType(x:Any) = x match { case s: String => println("String") case l: List[_] => println("List") case l: Map[_,_] => println("Map") case _ => println("Unhandled type!")}def factorial(n: Int): Int = n match { case 0 => 1 case x if x > 0 => factorial(n - 1) * n}
  56. 56. Clojure● Clojure is LISP● Dynamic language● Designed for the JVM● Code is data● Powerful macros● Good interoperability with Java● Clojure is fast● Concurrency. Shared Transactional Memory● 2007
  57. 57. Why Functional Programming? Referential transparencyλ Unit testingλ Debbugingλ Parallelizationλ Modularity and compositionλ Increases the quality of codeλ Abstractionsλ
  58. 58. Hello Clojure (println "Hello World")
  59. 59. Prefix notation (+ 1 2) => 3 (+ 1 2 3 4 5) => 15 (< 1 2 3 4 5) => true
  60. 60. Anatomy of a Function(defn biggest "Find the maximum of two numbers" [x y] (if (> x y) x y))
  61. 61. Anatomy of a Function(def biggest "Find the maximum of two numbers" (fn [x y] (if (> x y) x y)))
  62. 62. Function Composition (defn square [x] (* x x)) (square 21) => 441 (square (+ 2 5)) => 49
  63. 63. Function Composition (defn sum-of-squares [x y] (+ (square x) (square y))) (sum-of-squares 3 4) => 25
  64. 64. Immutability (def my-list (1 2 3)) +---+ +---+ +---+ | 1 | ---> | 2 | ---> | 3 | +---+ +---+ +---+ (def new-list (conj my-list 0)) +-----------------------------+ +---+ | +---+ +---+ +---+ | | 0 | --->| | 1 | ---> | 2 | ---> | 3 | | +---+ | +---+ +---+ +---+ | +-----------------------------+
  65. 65. Lazy EvaluationOnly does as much work as necessary Delays the evaluation of the expression until its neededCPU efficient The value is not calculated or assigned until the value is requestedManage potentially infinite data structures Only a manageable subset of the data will actually be used
  66. 66. Infinite Sequences (take 3 (repeat "Hello")) => ("Hello" "Hello" "Hello") (take 5 (cycle [1 2 3])) => (1 2 3 1 2) (take 5 (drop 2 (cycle [1 2 3]))) (->> [1 2 3] (cycle) (drop 2) (take 5)) (1 2 3 1 2 3 1 2 3 … => (3 1 2 3 1)
  67. 67. Clojure STM (def my-account (ref 1000.)) (def other-account (ref 5000.)) (defn transfer [from to amount] (dosync (alter from - amount) (alter to + amount))) (transfer other-account my-account 1000.)
  68. 68. Thank you!@ArturoHerrero
  1. A particular slide catching your eye?

    Clipping is a handy way to collect important slides you want to go back to later.

×