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

Scala for the doubters

Scala for the doubters

Scala overview and comparison with Java 8

Max Klyga

May 21, 2015
Tweet

More Decks by Max Klyga

Other Decks in Programming

Transcript

  1. Lightweight syntax object Main extends Application { val phonebook =

    Map( "Alice" -> "212-34-56", "Bob" -> "265-43-21" ) phonebook += ("Carl" -> "298-76-54") println(phonebook("Alice")) for (i <- 1 to 10) { println(i) } } Scala
  2. Lightweight syntax public class Person { private String firstName; private

    String lastName; String getFirstName() { return firstName; } void setFirstName(String firstName) { this.firstName = firstName; } String getLastName() { return lastName; } void setLastName(String lastName) { this.lastName = lastName; } int hashCode() { .... } boolean equals(Object o) { .... } } Java
  3. Lightweight syntax boolean hasUpperCase = false; for (int i =

    0; i < name.length(); ++i) { if (Character.isUpperCase(name.charAt(i))) { hasUpperCase = true; break; } } Java
  4. Lightweight syntax Predicate<Character> isUpperCase = new Predicate<Character>() { public Character

    apply(Character ch) { return Character.isUpperCase(ch); } }; boolean hasUpperCase = Iterables.any(Lists.charactersOf(name), isUpperCase); Java + Guava
  5. Lightweight syntax Predicate<Character> isUpperCase = (ch) -> Character.isUpperCase(ch); boolean hasUpperCase

    = Iterables.any(Lists.charactersOf(name), isUpperCase); Java 8 + Guava
  6. Lambdas Java 8 •Can only access final variables •Cannot mutate

    variables in outer scope Scala •Can access any variables •Can mutate any accessible variables
  7. Traits Java 8 •Can define default methods in interfaces (Java

    9 allows private methods) •“Diamond” inheritance is forbidden Scala •No restrictions on method implementation •Method invocation chain determined by inheritance order
  8. Composable class Eggs { def bacon { def inner(…) {

    def innerer { … } … } … } }
  9. Pattern matching sealed abstract class ChatProtocol case class Message(userId:Int, text:String)

    extends ChatProtocol case class Join(userId:Int, name:String) extends ChatProtocol case class Leave(userId:Int) extends ChatProtocol command match { case Message(id, text) => println(s"${users(id)}: ${text}") case Join(id, name) => { users += (id, name) println(s"${name} joined") } case Leave(id) => { println(s"${users(id)} left") users -= id } }
  10. So much more • Everything is an object • Limited

    type inference • Operator overloading (Everything is a method) • Algebraic data types • Partial functions • Tuples • Value classes
  11. Operator overloading abuse val intermediateHandler = (:/(host, port) / target

    <<? params >:> identity) https://github.com/dispatch/reboot def root = jsonObj | jsonArray def jsonObj = "{" ~> repsep(objEntry, ",") <~ "}" ^^ { case vals:List[_] => JSONObject(Map(vals:_*)) } def jsonArray = "[" ~> repsep(value, ",") <~ "]" ^^ { case vals:List[_] => JSONArray(vals) } def objEntry = stringVal ~ (":" ~> value) ^^ { case x ~ y => (x, y) } https://github.com/scala/scala-parser-combinators Unicode operators in ScalaZ: ≠ ∋ ≯ ★ ∅
  12. Learning Scala will make you a better Java programmer •

    Data transformation pipeline instead of CRUD • “Sane” error handling, data validation http://fsharpforfunandprofit.com/rop/ • Computation and data composition For comprehensions (Monads …)
  13. eDSL val orders = List[Order]( // use the default pricing

    strategy new Order to buy(200 sharesOf "GOOGLE") maxUnitPrice 300 using defaultPricing, // use a custom pricing strategy new Order to sell(200 bondsOf "Sun") maxUnitPrice 300 using { (qty, unit) => qty * unit - 500 } ) http://debasishg.blogspot.com/2008/05/designing-internal- dsls-in-scala.html
  14. eDSL class HelloWorldSpec extends Specification { def is = s2"""

    This is a specification for the 'Hello world' string The 'Hello world' string should contain 11 characters $e1 start with 'Hello' $e2 end with 'world' $e3 """ def e1 = "Hello world" must haveSize(11) def e2 = "Hello world" must startWith("Hello") def e3 = "Hello world" must endWith("world") } https://etorreborre.github.io/specs2/
  15. eDSL object SquareRoot extends Baysick { def main(args:Array[String]) = {

    10 PRINT "Enter a number" 20 INPUT 'n 30 PRINT "Square root of " % "'n is " % SQRT('n) 40 END RUN } } https://github.com/fogus/baysick
  16. Learn more • Twitter Scala school http://twitter.github.io/scala_school/ • Scala for

    the Impatient http://www.horstmann.com/scala/ • Programming in Scala http://www.artima.com/shop/programming_in_scala_2ed • Functional Programming in Scala http://manning.com/bjarnason/