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 ļ¬les
   ā€¢  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?
ā€¢ Simpliļ¬ed syntax
ā€¢ Functional programming
ā€¢ Dynamic-language features
  ā€¢   Mix-ins (traits)
  ā€¢   Structural types
  ā€¢   Implicits
  ā€¢   The Dynamic trait

ā€¢ Scala libraries
Simpliļ¬ed Syntax
ā€¢   Case classes
case class Person (ļ¬rstName:String, lastName:String)

ā€¢   Type inference
val m = new HashMap[Int, String]

ā€¢   No getters / setters
Unless you really need them

ā€¢   More ļ¬‚exible 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, ļ¬lter, ...
    ā€¢   Deļ¬ne your own control structures

ā€¢   Immutable eager and lazy values
ā€¢   Pattern matching
ā€¢   For comprehensions
Traits

ā€¢ Interfaces with method deļ¬nitions
ā€¢ 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 ļ¬rst 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 ļ¬rst 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
Ā 
java training faridabad
java training faridabadjava training faridabad
java training faridabadWoxa Technologies
Ā 
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
Ā 
Java SE 8 best practices
Java SE 8 best practicesJava SE 8 best practices
Java SE 8 best practicesStephen Colebourne
Ā 
Java 5 and 6 New Features
Java 5 and 6 New FeaturesJava 5 and 6 New Features
Java 5 and 6 New FeaturesJussi Pohjolainen
Ā 
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
Ā 
Scala introduction
Scala introductionScala introduction
Scala introductionYardena Meymann
Ā 
camel-scala.pdf
camel-scala.pdfcamel-scala.pdf
camel-scala.pdfHiroshi Ono
Ā 
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
Ā 
jQuery Objects
jQuery ObjectsjQuery Objects
jQuery ObjectsSteve Wells
Ā 
Scala for Java Programmers
Scala for Java ProgrammersScala for Java Programmers
Scala for Java ProgrammersEric Pederson
Ā 
Java 10, Java 11 and beyond
Java 10, Java 11 and beyondJava 10, Java 11 and beyond
Java 10, Java 11 and beyondRafael Winterhalter
Ā 
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
Ā 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajaxguestcf600a
Ā 
&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
Ā 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajaxguestcf600a
Ā 

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
Ā 
jQuery-1-Ajax
jQuery-1-AjaxjQuery-1-Ajax
jQuery-1-Ajax
Ā 
&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
Ā 
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

GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdflior mazor
Ā 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
Ā 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024The Digital Insurer
Ā 
Scaling API-first ā€“ The story of a global engineering organization
Scaling API-first ā€“ The story of a global engineering organizationScaling API-first ā€“ The story of a global engineering organization
Scaling API-first ā€“ The story of a global engineering organizationRadu Cotescu
Ā 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
Ā 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherRemote DBA Services
Ā 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
Ā 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
Ā 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
Ā 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoffsammart93
Ā 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
Ā 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
Ā 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
Ā 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
Ā 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUK Journal
Ā 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
Ā 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
Ā 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Principled Technologies
Ā 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel AraĆŗjo
Ā 

Recently uploaded (20)

+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
Ā 
GenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdfGenAI Risks & Security Meetup 01052024.pdf
GenAI Risks & Security Meetup 01052024.pdf
Ā 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
Ā 
Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024Partners Life - Insurer Innovation Award 2024
Partners Life - Insurer Innovation Award 2024
Ā 
Scaling API-first ā€“ The story of a global engineering organization
Scaling API-first ā€“ The story of a global engineering organizationScaling API-first ā€“ The story of a global engineering organization
Scaling API-first ā€“ The story of a global engineering organization
Ā 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
Ā 
Strategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a FresherStrategies for Landing an Oracle DBA Job as a Fresher
Strategies for Landing an Oracle DBA Job as a Fresher
Ā 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Ā 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Ā 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
Ā 
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot TakeoffStrategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Strategize a Smooth Tenant-to-tenant Migration and Copilot Takeoff
Ā 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
Ā 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
Ā 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
Ā 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Ā 
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdfUnderstanding Discord NSFW Servers A Guide for Responsible Users.pdf
Understanding Discord NSFW Servers A Guide for Responsible Users.pdf
Ā 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Ā 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Ā 
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Deploy with confidence: VMware Cloud Foundation 5.1 on next gen Dell PowerEdg...
Ā 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Ā 

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 ļ¬les ā€¢ 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? ā€¢ Simpliļ¬ed syntax ā€¢ Functional programming ā€¢ Dynamic-language features ā€¢ Mix-ins (traits) ā€¢ Structural types ā€¢ Implicits ā€¢ The Dynamic trait ā€¢ Scala libraries
  • 18. Simpliļ¬ed Syntax ā€¢ Case classes case class Person (ļ¬rstName:String, lastName:String) ā€¢ Type inference val m = new HashMap[Int, String] ā€¢ No getters / setters Unless you really need them ā€¢ More ļ¬‚exible 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, ļ¬lter, ... ā€¢ Deļ¬ne your own control structures ā€¢ Immutable eager and lazy values ā€¢ Pattern matching ā€¢ For comprehensions
  • 20. Traits ā€¢ Interfaces with method deļ¬nitions ā€¢ 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 ļ¬rst 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 ļ¬rst 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