Share
Embed
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
Transcript
66 slides
-
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 -
What is the session format? - Talks (Short/Long) - Lightning
Talks (5 mins) - Anything else you can think of -
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 -
What is the grand vision? - To build a community
of folks in the Bank who are aware and excited about technology -
What is in it for us? - Fosters learning and
growth - Community & Networking - Ideas, Inspirations, Collaboration -
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 -
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 -
Intranet Sharepoint - Lunch and Learn Sessions - External Tech
Meetups - Interesting Articles - Anything else you can think of -
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? -
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 -
My motivation for this talk How I feel like if
I have to code Java nowadays. -
JVM Languages in the Wild - Java - Scala -
Clojure - Groovy - JRuby -
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/ -
Who is using Scala in production? - Twitter - LinkedIn
- Novell - FourSquare - Électricité de France Trading - UBS - Bubbly -
Scala is a modern multi-paradigm programming language designed to express
common programming patterns in a concise, elegant, and type-safe way. -
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 -
Hello World object HelloWorld { def main(args:
Array[String]) { println("Hello, world!") } } -
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) -
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) } } -
Variables & Values // variable (mutable) var foo = "foo"
foo = "bar" // allowed // value (constant, final) val bar = "bar" bar = "foo" // not allowed -
Type Inference val sum = 1 + 2 + 3
val strings = List("Hello", "World") val numToStrings = Map(1 -‐> List("v1", "v2", "v3")) -
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")) -
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; } } -
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; } } -
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/ -
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) -
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/ -
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 -
Singleton Objects // Replaces static methods from Java // Can
extend/implement classes & traits object Hello { def world = println("Hello, world!") } Hello.world // -‐> "Hello, World" -
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. -
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 -
Lambda/Anonymous Functions // Lightweight anonymous functions (x:Int) => x -‐
1 // Calling it val minusOne = (x:Int) => x -‐ 1 minusOne(5) // -‐> 4 -
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 -
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) -
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 -
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) -
Pattern Matching val nums = List(1, 2, 3) val List(a,
b, _) = nums a // -‐> 1 b // -‐> 2 -
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) -
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/ -
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 ... -
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 -
Great Scala Libraries Akka Slick Scalatest Play Lift Spray.io Free
to use any Java library! -
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