Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Moving from Java to Scala, Multi-Paradigm Langu...

Moving from Java to Scala, Multi-Paradigm Language for the JVM

DBS ITT Lunch and Learn Tech Sharing June 2014

Speakers

1. Moving from Java to Scala, Multi-Paradigm Language for the JVM by Steve Teo

Steve Teo

June 12, 2014
Tweet

More Decks by Steve Teo

Other Decks in Technology

Transcript

  1. What is this all about? - Once a month lunchtime

    session - Focus on the learning and sharing of technology - Open to all folks who have a kin interest
  2. What is the session format? - Talks (Short/Long) - Lightning

    Talks (5 mins) - Anything else you can think of
  3. How did this come about? - Lack of a platform

    for learning/sharing of technology - My experience with tech meetups, conferences, etc. - Some encouragement from the folks around me
  4. What is the grand vision? - To build a community

    of folks in the Bank who are aware and excited about technology
  5. What is in it for us? - Fosters learning and

    growth - Community & Networking - Ideas, Inspirations, Collaboration
  6. What can people talk on? - Anything to do with

    technology - Something you have been up to - Something your team has been up to - Cool hacks - Anything else you can think of
  7. How can you contribute? - Be a speaker - Be

    a co-organiser - Be an attendee - Let others know about this - Give useful feedback - Anything else you can think of
  8. Intranet Sharepoint - Lunch and Learn Sessions - External Tech

    Meetups - Interesting Articles - Anything else you can think of
  9. Quick Survey - What is your main bread and butter

    language? - How many of you know there are alternative JVM languages? - How many of you have heard/developed using Scala? - How many of you know what functional programming is?
  10. My motivation for this talk - Keen interest in programming

    languages, especially those that support functional programming - Did 'Functional Programming Principles in Scala' on Coursera in 2013 https://www.coursera.org/course/progfun - Currently working on a mixed Scala/Java project, which was previously a pure Java project
  11. My motivation for this talk How I feel like if

    I have to code Java nowadays.
  12. Scala Facts - Designed by Martin Odersky (Generic Java/Javac fame),

    released publicly in 2004 - Initially designed for both JVM and .NET .NET support was dropped in 2012 - Part of the Typesafe stack, supported by Typesafe Inc. - Current Version: 2.11.1 - Free and Open Source http://scala-lang.org/
  13. Who is using Scala in production? - Twitter - LinkedIn

    - Novell - FourSquare - Électricité de France Trading - UBS - Bubbly
  14. Scala is a modern multi-paradigm programming language designed to express

    common programming patterns in a concise, elegant, and type-safe way.
  15. Main Characteristics - Runs on the JVM, full Inter-op with

    Java - Statically Typed - Multi-paradigm: Functional, Object-Oriented - Dynamic Languages Features eg. REPL, Lack of un-needed type annotation, Scripts
  16. Hello World object  HelloWorld  {        def  main(args:

     Array[String])  {                println("Hello,  world!")        } }
  17. Highly Interoperable with Java - Can be used as a

    drop-in replacement for Java Mixed Java/Scala Project due to mixed compilation support - Not an 'all or nothing' preposition - Deployment-wise, it's just a JAR - Scala Code compiles to Java Bytecode - Can use existing Java libraries - Can use existing Java tooling (Ant, Maven, Gradle, JUnit) - Decent IDE support (IntelliJ, Eclipse)
  18. Java Interop Example import  java.util.{Date,  Locale} import  java.text.DateFormat import  java.text.DateFormat._

    object  FrenchDate  {        def  main(args:  Array[String])  {                val  now  =  new  Date                val  df  =  getDateInstance(LONG,  Locale.FRANCE)                println(df  format  now)        } }
  19. Variables & Values //  variable  (mutable) var  foo  =  "foo"

    foo  =  "bar"  //  allowed //  value  (constant,  final) val  bar  =  "bar" bar  =  "foo"  //  not  allowed
  20. Type Inference val  sum  =  1  +  2  +  3

    val  strings  =  List("Hello",  "World") val  numToStrings  =  Map(1  -­‐>  List("v1",  "v2",  "v3"))
  21. Explicit Typing val  sum:  Int  =  1  +  2  +

     3 val  strings:  List[String]  =  List("Hello",  "World") val  numToStrings:  Map[Int,List[String]]  =  Map(1  -­‐>  List("v1",  "v2",  "v3"))
  22. Expressive //  Java  -­‐  Check  if  string  has  lowercase  character

    boolean  hasLowerCase  =  false; for(int  i  =  0;  i  <  name.length();  i++)  {        if(Character.isLowerCase(name.charAt(i)))  {                hasLowerCase  =  true;                break;        } }
  23. Less Boilerplate //  Java  -­‐  Does  this  look  familiar? public

     class  Person  {        private  String  name;        private  int  age;                public  Person(String  name,  int  age)  {                this.name  =  name;                this.age  =  age;        }                public  String  getName()  {                return  name;        }                public  int  getAge()  {                return  age;        }                public  void  setAge(int  age)  {                this.age  =  age;        } }
  24. Less Boilerplate //  Scala class  Person(val  name:  String,  private  var

     _age:  Int)  {        def  age  =  _age  //  Getter  for  age        def  age_=  (newAge:  Int)  {  //  Setter  for  age                println("Changing  age  to:  "  +  newAge)                _age  =  newAge        } } http://joelabrahamsson.com/learning-scala-part-nine-uniform-access/
  25. Everything is an object //  Numbers  are  objects  (No  primitives

     -­‐  eg.  ints,  arrays) 0.toString //  Operations  are  method  calls 0  +  1  +  2  //  -­‐>  (0).+(1).+(2) //  Functions  are  objects  (Covered  later)
  26. Traits Think of them as Interfaces that can provide concrete

    members. Solves multiple inheritance problems trait  Ord  {        def  <  (that:  Any):  Boolean        def  <=(that:  Any):  Boolean  =  (this  <  that)  ||  (this  ==  that)        def  >  (that:  Any):  Boolean  =  !(this  <=  that)        def  >=(that:  Any):  Boolean  =  !(this  <  that) } http://blog.safaribooksonline.com/2013/05/30/traits-how-scala-tames-multiple-inheritance/
  27. Traits vs Abstract Classes Abstract classes can have constructor parameters

    as well as type parameters. Traits can have only type parameters. Abstract classes are fully interoperable with Java. You can call them from Java code without any wrappers. Traits are fully interoperable only if they do not contain any implementation code
  28. Singleton Objects //  Replaces  static  methods  from  Java //  Can

     extend/implement  classes  &  traits object  Hello  {    def  world  =  println("Hello,  world!") } Hello.world  //  -­‐>  "Hello,  World"
  29. What is Functional Programming? In computer science, functional programming is

    a programming paradigm, a style of building the structure and elements of computer programs, that treats computation as the evaluation of mathematical functions and avoids state and mutable data.
  30. What is Functional Programming? - Functions are first class objects

    It is possible to pass functions as arguments, to store them in variables, and to return them from other functions. - Lambda/Anonymous Functions - Closures - Higher Order Functions - Others: Nesting, Currying
  31. Lambda/Anonymous Functions //  Lightweight  anonymous  functions (x:Int)  =>  x  -­‐

     1 //  Calling  it val  minusOne  =  (x:Int)  =>  x  -­‐  1 minusOne(5)  //  -­‐>  4
  32. Closures //  plusInitial  can  reference  any  values/variables  in  scope var

     initial  =  1 val  plusInitial  =  (x:Int)  =>  x  +  initial plusInitial(5)  //  -­‐>  6   //  Changing  initial  changes  the  return  value  of  plusInitial initial  =  5 plusInitial(5)  //  -­‐>  10
  33. Higher Order Functions Many of these exists in the collections

    library val  plusOne  =  (x:  Int)  =>  x  +  1 val  nums  =  List(1,  2,  3) //  maps  take  a  function:  Int  =>  T nums.map(plusOne) //  Inline  anonymous nums.map(x  =>  x  +  1) //  Even  shorter  form nums.map(_  +  1)
  34. Higher Order Functions val  nums  =  List(1,  2,  3,  4)

    nums.exists(_  ==  2)  //  =>  true nums.find(_  ==  2)  //  =>  Some(2) //  Reduce  uses  the  first  element  of  the  input  list  as  the  initial  accumulator  value. nums.reduceLeft(_  +  _)  //  =>  10 //  Fold  takes  an  explicit  initial  value  for  the  accumulator nums.foldLeft(100)(_  +  _)  //  =>  10
  35. Pattern Matching def  decipherType(any:  Any)  =  any  match  {  

         case  5  =>  "I  am  Five"        case  i:  Int  =>  "I  am  a  Int"        case  s:String  =>  "I  am  a  String"        case  _  =>  "Unknown" } decipherType(5) decipherType(123) decipherType("hello") decipherType(false)
  36. Pattern Matching val  nums  =  List(1,  2,  3) val  List(a,

     b,  _)  =  nums a  //  -­‐>  1 b  //  -­‐>  2
  37. Immutable Types //  Immutable  type  by  default var  nums  =

     Set(1,  2,  3) nums  +=  4  //  -­‐>  nums  =  nums.+(4) //  Mutable  types  available import  scala.collection.mutable_ var  nums  =  Set(1,  2,  3) nums  +=  4  //  -­‐>  nums.+(4)
  38. Built-in Concurrency Support - Favor Actors instead of Threads for

    Concurrency - Scala actors were deprecated in 2.10 in favor of Akka Actors - Futures for parallel operations http://www.scala-lang.org/old/node/242 http://akka.io/
  39. Scala, the Iceberg Most WTF Advanced Typing System Case Classes

    combined with Pattern Matching Optional For Comprehensions Default Parameter Values Named Parameters Lazy Vals Tuples ...
  40. Scala Downsides and Caveats - Steep learning curve in mastering

    idiomatic Scala - Slow compilation time - Binary compatibility - Not every thing is good about Scala. You need to figure out what is good and not good
  41. Final Thoughts - Scala is all about choices. Mix and

    match Imperative vs Functional? - Scala is a better Java, proven for Production Applications. - Java 8 won't kill Scala. It validates the existence of Scala and will only make it more popular. - Learn Scala not just as a language, but learn it for its concepts