SlideShare a Scribd company logo
1 of 52
Static or Dynamic Typing?
     Why Not Both?
       Mixing JRuby and Scala



           Mario Camou
            @thedoc
Agenda

• Why?
• Why Scala?
• Calling Scala from JRuby
• Calling JRuby from Scala
• Q&A
Why?
Why Not?


• The JVM allows us to mix-and-match
• Use the right tool for each part of
  the job
Why?

Ruby (and dynamic languages in general) are
great
•   Rapid development
•   Flexibility
•   Duck-typing
•   Metaprogramming
Why?


...but there are some pitfalls
•   Integration
•   Correctness
•   Performance
•   Productivity
Integration



JRuby gives you access to any Java libraries
and frameworks...
Integration
...but not all of them are JRuby-friendly
   (even though JRuby keeps getting better!)
   •  Class names and actual classes (beyond jrubyc)
   •  Method signatures
   •  Overloaded methods
   •  Type erasure in generics
   •  Subclassing
   •  Annotations
   •  Executable JAR files
   •  Legacy applications
Integration

Use statically-typed proxies to bridge the gap




      http://fffff.at/free-universal-construction-kit/
Correctness
 •   Static analysis

 •   Refactoring

 •   Self-documentation

 •   Type errors

 •   Unit tests can help...
     •   ...but they have to be complete...
     •   ...and they don’t cover all possible scenarios...
     •   ...and tracking down type errors can be Hell
http://evanfarrer.blogspot.com.es/2012/06/unit-testing-isnt-enough-you-need.html
Correctness
• Use a statically-typed language for critical or
  library code
• Use a dynamically-typed language for high-
  level dynamic code and DSLs
  http://olabini.com/blog/2008/06/fractal-programming/
Performance


JRuby performance is great and getting
better...
(and it doesn’t matter if the application is waiting for the
user 10 times faster)
Performance

• For some tasks, static typing can be faster
     •    Heavy computation
     •    Method lookup
     •    method_missing
     •    Some benchmarks:
  http://shootout.alioth.debian.org/u32/performance.php
Performance



Implement performance-critical tasks in a
compiled statically-typed language
Productivity


• Refactoring (again!)
• Code navigation
• IDE help (method parameters, autocomplete, ...)
Agenda

• Why?
• Why Scala?
• Calling Scala from JRuby
• Calling JRuby from Scala
• Q&A
Why Scala?
• Simplified syntax
• Functional programming
• Dynamic-language features
  •   Mix-ins (traits)
  •   Structural types
  •   Implicits
  •   The Dynamic trait

• Scala libraries
Simplified Syntax
•   Case classes
case class Person (firstName:String, lastName:String)

•   Type inference
val m = new HashMap[Int, String]

•   No getters / setters
Unless you really need them

•   More flexible method names (think DSLs)
Use (almost) any character
Translated to legal names in bytecode (i.e., + is $plus, += is $plus$eq)
Functional Programming

Mixed OO - Functional model
•   Closures / partial functions
    •   foreach, map, fold, filter, ...
    •   Define your own control structures

•   Immutable eager and lazy values
•   Pattern matching
•   For comprehensions
Traits

• Interfaces with method definitions
• Can be used for mix-ins
• Calling the previous method in the chain
  with no aliasing
• Dependency injection (“cake pattern”)
Structural Types
• Declare what you need, not the type
• Statically-typed duck typing
class Foo { def x = "Foo.x" }

class Bar { def x = "Bar.x" }

def doIt (arg: { def x:String }) = arg.x


scala> doIt(new Foo)
res0: String = Foo.x

scala> doIt(new Bar)
res1: String = Bar.x
Implicits

• Automatically convert one object to another type
• Solve some of the same problems as open classes
class MyRichString(str: String) {
  def acronym = str.toCharArray.foldLeft("") { (t, c) =>
    t + (if (c.isUpperCase) c.toString else "")
  }
}
 
implicit def str2MRString(str: String) = new MyRichString(str)


scala> "The HitchHiker's Guide To The Galaxy".acronym
res0: java.lang.String = THHGTTG
Implicits
In Scala:                                       In Ruby:
implicit def newLT(i: Int) = new {              class Fixnum
  def <(str: String) = i < str.length             alias_method :__old_lt, '<'.to_sym
}                                                 def <(target)
                                                    if target.kind_of? String
                                                      __old_lt__ target.size
scala> 1 < "foo"                                    else
res0: Boolean = false                                 __old_lt__ target
                                                    end
scala> 5 < "foo"                                  end
res1: Boolean = true                            end




http://www.codecommit.com/blog/ruby/implicit-conversions-more-powerful-than-dynamic-typing
The Dynamic Trait
  • Similar to method_missing
  • Experimental in 2.9, available in 2.10
object Test extends Dynamic {
  def applyDynamic (method:String) (args: Any*) {
    println ("%s (%s)".format(method, args.mkString(",")))
  }
}

scala> Test.foo("bar",'baz, 1)
foo (bar,'baz, 1)
Scala Libraries


• Akka
• Parser combinators
• Play / Lift / Scalatra / ...
Akka
• Based on the Actor model (Erlang)
• Message passing
• Transparent distribution
• Messaging system integration
 •   AMQP
 •   Apache Camel
 •   HTTP
 •   ...

• Software Transactional Memory
Akka

• Mikka: Actors in JRuby by Theo Hultberg
  (@iconara)
• Thin wrapper around Akka Java API to
  make it more Ruby-like
• https://github.com/iconara/mikka
• ...for more info ask Theo!
Agenda

• Why?
• Why Scala?
• Calling Scala from JRuby
• Calling JRuby from Scala
• Q&A
Calling Scala from JRuby


• Just like Java!
• JRuby sugar
  •   1.6.0+
  •   1.6.6+
Just like Java!
In Scala:                                 In JRuby:
package app.helpers                       require ‘java’
                                          => true
import scala.reflect.BeanProperty         f = Java::app.helpers.Foo.new
                                          => #<Java::AppHelpers::Foo:0x325bc91>
class Foo {                               f.q = "Life, the Universe and Everything"
  private var question: String = ""       => "Life, the Universe and Everything"
  @BeanProperty var a: String = ""        f.a = "42"
                                          => "42"
  def questionAndAnswer = "Unknowable"    f.q
                                          => "Life, the Universe and Everything"
  def setQ(s:String) = { question = s }
                                          f.a
  def getQ = question
                                          => "42"
}
                                          f.question_and_answer
                                          => "Unknowable"


  https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby
Just like Java!
     Functions / blocks / closures
In Scala:                             In JRuby:
package app.helpers                   f = Java::app.helpers.Foo.new
                                      => #<Java::AppHelpers::Foo:0x325bc91>
class Foo {                           f(1, 2, 3) { |x, y| x + y }
  def test(x:Int, y:Int, z:Int,       => true
           f:(Int, Int) => Int) = {
    f(x,y) == z
  }
}
JRuby Sugar - 1.6.0+

  Singleton (Scala object) support
  Call Singleton methods just like static/class methods


In Scala:                            In JRuby:

package app.helpers                  require ‘java’
                                     # => true
object Foo {                         Java::app.helpers.Foo.test
  def test = "Static method"         # => “Static method”
}
JRuby Sugar - 1.6.6+

 Operator aliases
 $plus -> +
 $minus -> -
 $div -> /
 $plus$eq -> +=
 apply (a.k.a. ()) -> []
 update (a.k.a. ()=) -> []=
 ...

               There are some caveats... see
https://github.com/jruby/jruby/wiki/Integrating-with-Scala
Agenda

• Why?
• Why Scala?
• Calling Scala from JRuby
• Calling JRuby from Scala
• Q&A
Calling JRuby from Scala



• JRuby Embed API (RedBridge / JSR-223)
• Scuby
JRuby Embed API

val container = new ScriptingContainer
val receiver = container.runScriptlet("""
# Radioactive decay
def amount_after_years(q0, t)
  q0 * Math.exp(1.0 / $half_life * Math.log(1.0/2.0) * t)
end
def years_to_amount(q0, q)
  $half_life * (Math.log(q) - Math.log(q0)) / Math.log(1.0/2.0)
end
""")
container.put("$half_life", 24100) // Plutonium
val args = Array[Object](10.0:java.lang.Double, 1000:java.lang.Integer)
val result = container.callMethod("amount_after_years", args, Double.class)




        https://github.com/jruby/jruby/wiki/RedBridgeExamples
Scuby


• Goals
• Assumptions and defaults
• Usage and examples
• Future steps
Scuby Goals


• Thin DSL layer between Scala and JRuby
• Simplify calling JRuby
• Calling JRuby should be as transparent as possible
• Static typing as far as possible
Assumptions & Defaults
•   Single JRuby engine
    •   For our needs, we don’t need more
    •   You don’t have to pass in the engine to every call

•   Singleton interpreter scope (default)
    •   Otherwise you can get things like nil != nil
    •   Can be changed before first JRuby call

•   Transient local variable behavior (default)
    •   Local variables don’t survive multiple evaluations
    •   If you need them to persist, store in a Scala val (and pass as
        parameter)...
    •   ...or change before first JRuby call
Usage

• require & eval
• Creating objects
• Calling methods
• Convenience methods
• Additional facilities
Example Ruby File
# File test.rb (from the Scuby tests)
module Core
  class Person
    attr_accessor :firstname, :lastname
    def initialize (firstname, lastname)
      @firstname = firstname
      @lastname = lastname
   end

    def fullname
      "#{firstname} #{lastname}"
    end

    def get_label
      javax.swing.JLabel.new(fullname)
    end
  end

...
Example Ruby File
...

  module Backend
   def self.get_people
      # Get data from the backend and return an Array of Person
    end

    def self.get_data
      { :people => get_people, :other_data => get_other_data }
    end

    def self.get_person(name)
      # Get a person's data from the DB and return a Person object
    end

    def self.get_other_data
      # Get some other data that is needed for the app
    end
  end
end
require & eval

import cc.abstra.scuby.JRuby._

// Require a Ruby file from the classpath
require("test")

// Eval a Ruby statement discarding the return value
eval("import Core")

// Eval a Ruby statement that returns a Ruby object
val array = eval[RubyObj]("[]")

// Or with type inference
val array2:RubyObj = eval("[]")
Creating Objects

import cc.abstra.scuby._

// Create a Ruby object
val array3 = new RubyObject('Array)

// Create a proxy object for the Ruby BackEnd class
val backend = RubyClass('Backend)

// Create an instance of the Person class
val person = new RubyObject('Person, "Zaphod", "Beeblebrox")
val person2 = RubyClass('Person) ! ('new, "Ford", "Prefect")
Calling Methods
    // Call a method on a Ruby object (in this case, the Ruby class),
    // passing in parameters, and get back another Ruby object
    val zaphod = backend ! ('get_person, "Zaphod")

    // Call a Ruby method with no parameters
    val data = backend ! 'get_data

    // Ruby method chaining
    val length = backend ! 'get_people ! 'length

    // Get a reference to a Ruby method that can later be called
    val getPerson = backend --> 'get_person

    // Call the method. Returns an AnyRef.
    // With the above, these 2 lines are equivalent:
    getPerson("Zaphod")
    backend('get_person, "Zaphod")

    // Call a Ruby method which returns a Java object,
    // in a type-safe way
    val label = person.send[JLabel]('get_label)
Arrays and Hashes

// Access to a Ruby Hash or Array (i.e., anything that implements [])
// and creating a Ruby Symbol using %
val people = data(%('people))
val zaphod2 = people(0)

// Multidimensional Hashes or Arrays (i.e., data["parm1"]["parm2"])
val ford = data(%('people), 1)

// Modify/add an element to a Hash or Array (or anything that
// implements []=)
people(2) = RubyClass('Person) ! ('new, "Arthur", "Dent")
Convenience Methods
• toString, equals, hashCode
   •   Forwarded to their Ruby equivalents (#to_s, #==,
       #hash)

• respondTo_?
       array3 respondTo_? 'length // true
       array3 respondTo_? 'foo       // false


• isA_?
       array3 isA_? 'Array // true
       array3 isA_? 'Hash   // false
Wrapping in Traits
trait   Person {
  def   firstname: String
  def   firstname_=(f: String): Unit
  def   lastname: String
  def   lastname_=(l: String): Unit
  def   fullname: String
  def   getLabel: JLabel
}

val zaphod = backend('get_person, "Zaphod").as[Person]
zaphod.firstname = "The Zeeb"
println(zaphod.fullname)
val label = zaphod.getLabel
Usage
To use Scuby:
 • Use the Source! (Pull requests welcome)
   •   https://github.com/abstracc/scuby
   •   Build using Maven
 • Download the compiled artifacts
   •   https://oss.sonatype.org/content/repositories/releases/cc/abstra/
       pasilla/scuby/0.1.8/
   •   You also need scala-library-2.9.2.jar and jruby-complete-1.6.7.jar
   •   Add all the .jar’s to your CLASSPATH
 • Use Maven (or SBT, Gradle, ...)
   •   groupId: cc.abstra.pasilla
   •   artifactId: scuby
   •   Current version: 0.1.8
Future Steps
• Scala side
  •   Ruby collections
  •   Java-friendly API
  •   Optimization

• Ruby side
  •   Create a Scuby gem
  •   FunctionN -> block conversion
  •   Wrapping Scala collections
  •   Object#to_scala
  •   scala top-level function (so we can, i.e., import scala.*)
Agenda

• Why?
• Why Scala?
• Calling Scala from JRuby
• Calling JRuby from Scala
• Q&A
Thank you
         Mario Camou
          @thedoc

http://github.com/abstracc/scuby
   http://github.com/mcamou
       http://www.abstra.cc

  Special thanks to @MadridJUG

More Related Content

What's hot

JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015Charles Nutter
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Yardena Meymann
 
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!scalaconfjp
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Down the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM WonderlandDown the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM WonderlandCharles Nutter
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern JavaSina Madani
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersMiles Sabin
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the futureAnsviaLab
 
Scala Matsuri 2016: Japanese Text Mining with Scala and Spark
Scala Matsuri 2016: Japanese Text Mining with Scala and SparkScala Matsuri 2016: Japanese Text Mining with Scala and Spark
Scala Matsuri 2016: Japanese Text Mining with Scala and SparkEduardo Gonzalez
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to ScalaTim Underwood
 

What's hot (18)

JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015JRuby and Invokedynamic - Japan JUG 2015
JRuby and Invokedynamic - Japan JUG 2015
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
Java 7 New Features
Java 7 New FeaturesJava 7 New Features
Java 7 New Features
 
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
What's a macro?: Learning by Examples / Scalaのマクロに実用例から触れてみよう!
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
java training faridabad
java training faridabadjava training faridabad
java training faridabad
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
Down the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM WonderlandDown the Rabbit Hole: An Adventure in JVM Wonderland
Down the Rabbit Hole: An Adventure in JVM Wonderland
 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practices
 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New Features
 
A brief tour of modern Java
A brief tour of modern JavaA brief tour of modern Java
A brief tour of modern Java
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
Scala : language of the future
Scala : language of the futureScala : language of the future
Scala : language of the future
 
Scala Matsuri 2016: Japanese Text Mining with Scala and Spark
Scala Matsuri 2016: Japanese Text Mining with Scala and SparkScala Matsuri 2016: Japanese Text Mining with Scala and Spark
Scala Matsuri 2016: Japanese Text Mining with Scala and Spark
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdf
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 

Similar to Static or Dynamic Typing? Why not both?

The Enterprise Strikes Back
The Enterprise Strikes BackThe Enterprise Strikes Back
The Enterprise Strikes BackBurke Libbey
 
Scala In The Wild
Scala In The WildScala In The Wild
Scala In The Wilddjspiewak
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)mircodotta
 
Intro to scala
Intro to scalaIntro to scala
Intro to scalaJoe Zulli
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryPray Desai
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Nayden Gochev
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos3Pillar Global
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevMattias Karlsson
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffJAX London
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformationLars Marius Garshol
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp DeveloperSarvesh Kushwaha
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxtutorialsruby
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />tutorialsruby
 

Similar to Static or Dynamic Typing? Why not both? (20)

The Enterprise Strikes Back
The Enterprise Strikes BackThe Enterprise Strikes Back
The Enterprise Strikes Back
 
Scala In The Wild
Scala In The WildScala In The Wild
Scala In The Wild
 
Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)Effective Scala (JavaDay Riga 2013)
Effective Scala (JavaDay Riga 2013)
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Scala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud FoundryScala, Play 2.0 & Cloud Foundry
Scala, Play 2.0 & Cloud Foundry
 
jQuery Objects
jQuery ObjectsjQuery Objects
jQuery Objects
 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java Programmers
 
Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyond
 
Java >= 9
Java >= 9Java >= 9
Java >= 9
 
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
Lecture from javaday.bg by Nayden Gochev/ Ivan Ivanov and Mitia Alexandrov
 
Scala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian DragosScala: Object-Oriented Meets Functional, by Iulian Dragos
Scala: Object-Oriented Meets Functional, by Iulian Dragos
 
Java 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from OredevJava 7 Whats New(), Whats Next() from Oredev
Java 7 Whats New(), Whats Next() from Oredev
 
Spring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard WolffSpring Day | Spring and Scala | Eberhard Wolff
Spring Day | Spring and Scala | Eberhard Wolff
 
JSLT: JSON querying and transformation
JSLT: JSON querying and transformationJSLT: JSON querying and transformation
JSLT: JSON querying and transformation
 
JavaScript For CSharp Developer
JavaScript For CSharp DeveloperJavaScript For CSharp Developer
JavaScript For CSharp Developer
 
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptxMicrosoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
Microsoft PowerPoint - &lt;b>jQuery&lt;/b>-1-Ajax.pptx
 
&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />&lt;img src="../i/r_14.png" />
&lt;img src="../i/r_14.png" />
 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 

Recently uploaded

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfPrecisely
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brandgvaughan
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Scott Keck-Warren
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubKalema Edgar
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024Lonnie McRorey
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity PlanDatabarracks
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdfHyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
Hyperautomation and AI/ML: A Strategy for Digital Transformation Success.pdf
 
WordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your BrandWordPress Websites for Engineers: Elevate Your Brand
WordPress Websites for Engineers: Elevate Your Brand
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024Advanced Test Driven-Development @ php[tek] 2024
Advanced Test Driven-Development @ php[tek] 2024
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Unleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding ClubUnleash Your Potential - Namagunga Girls Coding Club
Unleash Your Potential - Namagunga Girls Coding Club
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024TeamStation AI System Report LATAM IT Salaries 2024
TeamStation AI System Report LATAM IT Salaries 2024
 
How to write a Business Continuity Plan
How to write a Business Continuity PlanHow to write a Business Continuity Plan
How to write a Business Continuity Plan
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
DMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special EditionDMCC Future of Trade Web3 - Special Edition
DMCC Future of Trade Web3 - Special Edition
 

Static or Dynamic Typing? Why not both?

  • 1. Static or Dynamic Typing? Why Not Both? Mixing JRuby and Scala Mario Camou @thedoc
  • 2. Agenda • Why? • Why Scala? • Calling Scala from JRuby • Calling JRuby from Scala • Q&A
  • 4. Why Not? • The JVM allows us to mix-and-match • Use the right tool for each part of the job
  • 5. Why? Ruby (and dynamic languages in general) are great • Rapid development • Flexibility • Duck-typing • Metaprogramming
  • 6. Why? ...but there are some pitfalls • Integration • Correctness • Performance • Productivity
  • 7. Integration JRuby gives you access to any Java libraries and frameworks...
  • 8. Integration ...but not all of them are JRuby-friendly (even though JRuby keeps getting better!) • Class names and actual classes (beyond jrubyc) • Method signatures • Overloaded methods • Type erasure in generics • Subclassing • Annotations • Executable JAR files • Legacy applications
  • 9. Integration Use statically-typed proxies to bridge the gap http://fffff.at/free-universal-construction-kit/
  • 10. Correctness • Static analysis • Refactoring • Self-documentation • Type errors • Unit tests can help... • ...but they have to be complete... • ...and they don’t cover all possible scenarios... • ...and tracking down type errors can be Hell http://evanfarrer.blogspot.com.es/2012/06/unit-testing-isnt-enough-you-need.html
  • 11. Correctness • Use a statically-typed language for critical or library code • Use a dynamically-typed language for high- level dynamic code and DSLs http://olabini.com/blog/2008/06/fractal-programming/
  • 12. Performance JRuby performance is great and getting better... (and it doesn’t matter if the application is waiting for the user 10 times faster)
  • 13. Performance • For some tasks, static typing can be faster • Heavy computation • Method lookup • method_missing • Some benchmarks: http://shootout.alioth.debian.org/u32/performance.php
  • 14. Performance Implement performance-critical tasks in a compiled statically-typed language
  • 15. Productivity • Refactoring (again!) • Code navigation • IDE help (method parameters, autocomplete, ...)
  • 16. Agenda • Why? • Why Scala? • Calling Scala from JRuby • Calling JRuby from Scala • Q&A
  • 17. Why Scala? • Simplified syntax • Functional programming • Dynamic-language features • Mix-ins (traits) • Structural types • Implicits • The Dynamic trait • Scala libraries
  • 18. Simplified Syntax • Case classes case class Person (firstName:String, lastName:String) • Type inference val m = new HashMap[Int, String] • No getters / setters Unless you really need them • More flexible method names (think DSLs) Use (almost) any character Translated to legal names in bytecode (i.e., + is $plus, += is $plus$eq)
  • 19. Functional Programming Mixed OO - Functional model • Closures / partial functions • foreach, map, fold, filter, ... • Define your own control structures • Immutable eager and lazy values • Pattern matching • For comprehensions
  • 20. Traits • Interfaces with method definitions • Can be used for mix-ins • Calling the previous method in the chain with no aliasing • Dependency injection (“cake pattern”)
  • 21. Structural Types • Declare what you need, not the type • Statically-typed duck typing class Foo { def x = "Foo.x" } class Bar { def x = "Bar.x" } def doIt (arg: { def x:String }) = arg.x scala> doIt(new Foo) res0: String = Foo.x scala> doIt(new Bar) res1: String = Bar.x
  • 22. Implicits • Automatically convert one object to another type • Solve some of the same problems as open classes class MyRichString(str: String) {   def acronym = str.toCharArray.foldLeft("") { (t, c) =>     t + (if (c.isUpperCase) c.toString else "")   } }   implicit def str2MRString(str: String) = new MyRichString(str) scala> "The HitchHiker's Guide To The Galaxy".acronym res0: java.lang.String = THHGTTG
  • 23. Implicits In Scala: In Ruby: implicit def newLT(i: Int) = new { class Fixnum   def <(str: String) = i < str.length   alias_method :__old_lt, '<'.to_sym }   def <(target)     if target.kind_of? String       __old_lt__ target.size scala> 1 < "foo"     else res0: Boolean = false       __old_lt__ target     end scala> 5 < "foo"   end res1: Boolean = true end http://www.codecommit.com/blog/ruby/implicit-conversions-more-powerful-than-dynamic-typing
  • 24. The Dynamic Trait • Similar to method_missing • Experimental in 2.9, available in 2.10 object Test extends Dynamic {   def applyDynamic (method:String) (args: Any*) {     println ("%s (%s)".format(method, args.mkString(",")))   } } scala> Test.foo("bar",'baz, 1) foo (bar,'baz, 1)
  • 25. Scala Libraries • Akka • Parser combinators • Play / Lift / Scalatra / ...
  • 26. Akka • Based on the Actor model (Erlang) • Message passing • Transparent distribution • Messaging system integration • AMQP • Apache Camel • HTTP • ... • Software Transactional Memory
  • 27. Akka • Mikka: Actors in JRuby by Theo Hultberg (@iconara) • Thin wrapper around Akka Java API to make it more Ruby-like • https://github.com/iconara/mikka • ...for more info ask Theo!
  • 28. Agenda • Why? • Why Scala? • Calling Scala from JRuby • Calling JRuby from Scala • Q&A
  • 29. Calling Scala from JRuby • Just like Java! • JRuby sugar • 1.6.0+ • 1.6.6+
  • 30. Just like Java! In Scala: In JRuby: package app.helpers require ‘java’ => true import scala.reflect.BeanProperty f = Java::app.helpers.Foo.new => #<Java::AppHelpers::Foo:0x325bc91> class Foo { f.q = "Life, the Universe and Everything"   private var question: String = "" => "Life, the Universe and Everything"   @BeanProperty var a: String = "" f.a = "42" => "42"   def questionAndAnswer = "Unknowable" f.q => "Life, the Universe and Everything"   def setQ(s:String) = { question = s } f.a   def getQ = question => "42" } f.question_and_answer => "Unknowable" https://github.com/jruby/jruby/wiki/CallingJavaFromJRuby
  • 31. Just like Java! Functions / blocks / closures In Scala: In JRuby: package app.helpers f = Java::app.helpers.Foo.new => #<Java::AppHelpers::Foo:0x325bc91> class Foo { f(1, 2, 3) { |x, y| x + y }   def test(x:Int, y:Int, z:Int, => true            f:(Int, Int) => Int) = {     f(x,y) == z   } }
  • 32. JRuby Sugar - 1.6.0+ Singleton (Scala object) support Call Singleton methods just like static/class methods In Scala: In JRuby: package app.helpers require ‘java’ # => true object Foo { Java::app.helpers.Foo.test   def test = "Static method" # => “Static method” }
  • 33. JRuby Sugar - 1.6.6+ Operator aliases $plus -> + $minus -> - $div -> / $plus$eq -> += apply (a.k.a. ()) -> [] update (a.k.a. ()=) -> []= ... There are some caveats... see https://github.com/jruby/jruby/wiki/Integrating-with-Scala
  • 34. Agenda • Why? • Why Scala? • Calling Scala from JRuby • Calling JRuby from Scala • Q&A
  • 35. Calling JRuby from Scala • JRuby Embed API (RedBridge / JSR-223) • Scuby
  • 36. JRuby Embed API val container = new ScriptingContainer val receiver = container.runScriptlet(""" # Radioactive decay def amount_after_years(q0, t) q0 * Math.exp(1.0 / $half_life * Math.log(1.0/2.0) * t) end def years_to_amount(q0, q) $half_life * (Math.log(q) - Math.log(q0)) / Math.log(1.0/2.0) end """) container.put("$half_life", 24100) // Plutonium val args = Array[Object](10.0:java.lang.Double, 1000:java.lang.Integer) val result = container.callMethod("amount_after_years", args, Double.class) https://github.com/jruby/jruby/wiki/RedBridgeExamples
  • 37. Scuby • Goals • Assumptions and defaults • Usage and examples • Future steps
  • 38. Scuby Goals • Thin DSL layer between Scala and JRuby • Simplify calling JRuby • Calling JRuby should be as transparent as possible • Static typing as far as possible
  • 39. Assumptions & Defaults • Single JRuby engine • For our needs, we don’t need more • You don’t have to pass in the engine to every call • Singleton interpreter scope (default) • Otherwise you can get things like nil != nil • Can be changed before first JRuby call • Transient local variable behavior (default) • Local variables don’t survive multiple evaluations • If you need them to persist, store in a Scala val (and pass as parameter)... • ...or change before first JRuby call
  • 40. Usage • require & eval • Creating objects • Calling methods • Convenience methods • Additional facilities
  • 41. Example Ruby File # File test.rb (from the Scuby tests) module Core   class Person     attr_accessor :firstname, :lastname     def initialize (firstname, lastname)       @firstname = firstname       @lastname = lastname    end     def fullname       "#{firstname} #{lastname}"     end     def get_label       javax.swing.JLabel.new(fullname)     end   end ...
  • 42. Example Ruby File ...   module Backend    def self.get_people       # Get data from the backend and return an Array of Person     end     def self.get_data       { :people => get_people, :other_data => get_other_data }     end     def self.get_person(name)       # Get a person's data from the DB and return a Person object     end     def self.get_other_data       # Get some other data that is needed for the app     end   end end
  • 43. require & eval import cc.abstra.scuby.JRuby._ // Require a Ruby file from the classpath require("test") // Eval a Ruby statement discarding the return value eval("import Core") // Eval a Ruby statement that returns a Ruby object val array = eval[RubyObj]("[]") // Or with type inference val array2:RubyObj = eval("[]")
  • 44. Creating Objects import cc.abstra.scuby._ // Create a Ruby object val array3 = new RubyObject('Array) // Create a proxy object for the Ruby BackEnd class val backend = RubyClass('Backend) // Create an instance of the Person class val person = new RubyObject('Person, "Zaphod", "Beeblebrox") val person2 = RubyClass('Person) ! ('new, "Ford", "Prefect")
  • 45. Calling Methods     // Call a method on a Ruby object (in this case, the Ruby class),     // passing in parameters, and get back another Ruby object     val zaphod = backend ! ('get_person, "Zaphod")     // Call a Ruby method with no parameters     val data = backend ! 'get_data     // Ruby method chaining     val length = backend ! 'get_people ! 'length     // Get a reference to a Ruby method that can later be called     val getPerson = backend --> 'get_person     // Call the method. Returns an AnyRef.     // With the above, these 2 lines are equivalent:     getPerson("Zaphod")     backend('get_person, "Zaphod")     // Call a Ruby method which returns a Java object, // in a type-safe way     val label = person.send[JLabel]('get_label)
  • 46. Arrays and Hashes // Access to a Ruby Hash or Array (i.e., anything that implements []) // and creating a Ruby Symbol using % val people = data(%('people)) val zaphod2 = people(0) // Multidimensional Hashes or Arrays (i.e., data["parm1"]["parm2"]) val ford = data(%('people), 1) // Modify/add an element to a Hash or Array (or anything that // implements []=) people(2) = RubyClass('Person) ! ('new, "Arthur", "Dent")
  • 47. Convenience Methods • toString, equals, hashCode • Forwarded to their Ruby equivalents (#to_s, #==, #hash) • respondTo_? array3 respondTo_? 'length // true array3 respondTo_? 'foo // false • isA_? array3 isA_? 'Array // true array3 isA_? 'Hash // false
  • 48. Wrapping in Traits trait Person {   def firstname: String   def firstname_=(f: String): Unit   def lastname: String   def lastname_=(l: String): Unit   def fullname: String   def getLabel: JLabel } val zaphod = backend('get_person, "Zaphod").as[Person] zaphod.firstname = "The Zeeb" println(zaphod.fullname) val label = zaphod.getLabel
  • 49. Usage To use Scuby: • Use the Source! (Pull requests welcome) • https://github.com/abstracc/scuby • Build using Maven • Download the compiled artifacts • https://oss.sonatype.org/content/repositories/releases/cc/abstra/ pasilla/scuby/0.1.8/ • You also need scala-library-2.9.2.jar and jruby-complete-1.6.7.jar • Add all the .jar’s to your CLASSPATH • Use Maven (or SBT, Gradle, ...) • groupId: cc.abstra.pasilla • artifactId: scuby • Current version: 0.1.8
  • 50. Future Steps • Scala side • Ruby collections • Java-friendly API • Optimization • Ruby side • Create a Scuby gem • FunctionN -> block conversion • Wrapping Scala collections • Object#to_scala • scala top-level function (so we can, i.e., import scala.*)
  • 51. Agenda • Why? • Why Scala? • Calling Scala from JRuby • Calling JRuby from Scala • Q&A
  • 52. Thank you Mario Camou @thedoc http://github.com/abstracc/scuby http://github.com/mcamou http://www.abstra.cc Special thanks to @MadridJUG

Editor's Notes

  1. \n
  2. \n
  3. \n
  4. \n
  5. \n
  6. \n
  7. \n
  8. \n
  9. \n
  10. \n
  11. \n
  12. \n
  13. \n
  14. \n
  15. \n
  16. \n
  17. \n
  18. \n
  19. \n
  20. \n
  21. \n
  22. \n
  23. \n
  24. \n
  25. \n
  26. \n
  27. \n
  28. \n
  29. \n
  30. \n
  31. \n
  32. \n
  33. \n
  34. \n
  35. \n
  36. \n
  37. \n
  38. \n
  39. \n
  40. \n
  41. \n
  42. \n
  43. \n
  44. \n
  45. \n
  46. \n
  47. \n
  48. \n
  49. \n
  50. \n
  51. \n
  52. \n