SlideShare a Scribd company logo
Scala in Nokia Places API


Lukasz Balamut - Places API Team




         17 April 2013
Purpose of this talk




        Why are we spending time migrating to a new language?
        How are we doing that?
        What have we learned?

    and of course: we are hiring.
Our scala story.

    Our migration in lines of code




    We’ve discovered more and more things on the way.
The Concordion tests problem
    In June 2011 we had problems with Concordion (HTML based acceptance test
    framework),

        hard to integrate
        HTML tests were not readable

    Solution:

        Multi-line Strings in Scala
        Continue using JUnit

    val expectedBody = """
      {
        "id":"250u09wh-83d4c5479b7c4db9836602936dbc8cb8",
        "title" : "Marfil (Le)",
        "alternativeNames" : [
            {
                "name" : "Le Marfil",
                "language" : "fr"
            }
        ]
    }
    """
The test names problem
       JUnit + camel case - not that readable for long names

   @Test
   def preservesSearchResponseItemOrder() { /* ... */ }

       JUnit + underscores - violates naming convention, but better to read

   @Test
   def preserves_search_response_item_order() { /* ... */ }

       ScalaTest

   test("preserves search response’s item order") { /* ... */ }

   It is supported by tools we use and produces nice output when run (as a bonus)

   [info]   DiscoverAroundAcceptanceTest:
   [info]   - calls nsp with 15Km radius
   [info]   - preserves search response’s item order
   [info]   - when requesting zero results, no request to search is made
Lift-Json


         JSON (de)serialisation can be done in really nice way

    e.g. getting place id:

    {
         "place": {
             "a_id": "276u33db-6f084959f97c45bc9db26348bafd4563"
           }
    }

    Also there is a generic way of parsing json, that gives you XPath like access:

    val id = (json  "place"  "a_id").extract[String]

         Lift-json provides also easy and efficient case class JSON (de)serialisation,
         hance case classes
Scala case classes in the model
    We model our upstream and downstream datamodels as case classes.
    case class Place (
      name: String,

        placeId: PlaceID
        //(...)
    )

         Each case class is a proper immutable data type - the new Java Bean ;),
         A lot of boilerplate code is generated by the compiler e.g.:
             accessors,
             equals/hashCode,
             copy methods,
             toString
             apply/unapply (for pattern maching),

    After decompiling the scala code above we will end up with 191 lines of Java:
    package pbapi.model.api;

    import   scala.*;
    import   scala.collection.Iterator;
    import   scala.runtime.BoxesRunTime;
    import   scala.runtime.ScalaRunTime$;
Scala case classes - Configuration

        Easy to update configuration
        Easy to compare environments’ configuration

    case class HttpClientConfig(
          serviceName: String,
          serviceBaseUrl: URL,
          readTimeout: Int = 0,
          connectionTimeout: Int,
          proxy: Option[ProxyConfig] = None,
          oauthKeys: Option[OAuthConfig] = None,
          displayUrl: Option[String] = None
    )

    "httpConfig":{
      "serviceName":"recommendations",
      "serviceBaseUrl":"http://nose.svc.ovi.com/rest/v1/recommendations/near
      "readTimeout":4000,
      "connectionTimeout":500,
      "displayUrl":"http://nose.svc.ovi.com/rest/v1/recommendations/nearby/"
    }
The Scala Type System




       A great way to express assumptions
       Have them checked by the compiler through the whole codebase
       At every point in the code know what to expect or you will be reminded by
       compiler.
The Scala Type System - Options 1




        Avoid null references (see The Billion Dollar Mistake )

    This will not compile!

    case class UpstreamResponse ( unreliableField: Option[String] )

    case class MyResponse ( reliableField: String )

    def transform(upstream: UpstreamResponse) =
        MyResponse(
            reliableField = upstream.unreliableField //<-- incompatible type
        )
The Scala Type System - Options 2




    But this will:

    case class UpstreamResponse ( unreliableField: Option[String] )

    case class MyResponse ( reliableField: String )

    def transform(upstream: UpstreamResponse) =
        MyResponse(
            reliableField = upstream.unreliableField.getOrElse("n/a") // enf
        )
The Scala Type System - Options 3


    how we were learning e.g.: to transform string when it is defined

    def transform(str: String): String

    reliableField =
        if (upstream.unreliableField.isDefined)
            transform(upstream.unreliableField.get)
        else "n/a"

    reliableField =
        upstream.unreliableField match {
            case Some(f) => transform(f)
            case None    => "n/a"
        }

    reliableField =
        upstream.unreliableField.map(transform) | "n/a"
The Scala Type System - Standard Types




       Immutable Map, List, Sets

   val map: Map[String, String] = Map("a" -> "a", "b" -> "b")

   val list: List[String] = "a" :: "b" :: Nil

       Tuples to express Pairs, Triplets etc.

   val pair: Pair[String, Int] = ("a", 1)

   val (a, b) = pair // defines a:String and b:Int
The Scala Type System - error handling
        Types can help with exceptional cases
    val parsed: Validation[NumberFormatException, Int] = someString.parseInt

    val optional: Option[Int] = parsed.toOption

    val withDefault: Int = optional.getOrElse(0) //if there was parsing prob

        Exception to Option
    val sub: Option[String] =
        allCatch.opt(line.substring(line.indexOf("{"")))

        or Either
    val parsed: Either[Throwable, Incident] =
        allCatch.either(new Incident(parse(jsonString))
    and handle it later
    parsed match {
        case Right(j) => Some(j)
        case Left(t) => {
            println("Parse error %s".format(t.getMessage))
            None
The Scala Type System - functions


        we defer translation (Translated) and text rendering (FormattedText) to
        serialisation time using function composition so we don’t need to pass user
        context through the whole stack e.g.:

    case class Place (
      //(...)
      attribution: Option[Translated[FormattedText]],
      //(...)
    )

    case class Translated[A](translator: TransEnv => A) {
        def apply(env: TransEnv): A = translator(env)

        def map[B](f: A => B): Translated[B] =
            new Translated[B](env => f(apply(env)))
        //(...)
    }
XML literals

    XML can be part of the code and compiler is checking syntax of it:

    def toKmlCoordinates(style: String): String         =
        (<Placemark>
            <name>{"bbox " + this}</name>
            <styleUrl>{style}</styleUrl>
            <Polygon>
                <outerBoundaryIs>
                    <LinearRing>
                        <coordinates>
                            {west + "," + north         +   ",0"}
                            {east + "," + north         +   ",0"}
                            {east + "," + south         +   ",0"}
                            {west + "," + south         +   ",0"}
                            {west + "," + north         +   ",0"}
                        </coordinates>
                    </LinearRing>
                </outerBoundaryIs>
            </Polygon>
        </Placemark>).toString
Scalacheck
    Automatic testing of assumptions, using set of generated values.
    e.g. the code below tests if
    BBox.parse(a.toString) == a
    is true for any a
    val generator: Gen[BBox] =
        for {
            s <- choose(-90.0, 90.0)
            n <- choose(-90.0, 90.0)
            if (n > s)
            w <- choose(-180.0, 180.0)
            e <- choose(-180.0, 180.0)
        } yield new BBox(w, s, e, n)

    property("parse . toString is identity") {
        check {
            (a: BBox) =>
                BBox.parse(a.toString) == a
        }
    }
    may yield this failing test message after several evaluations.
Scala (Scalding) in our analytics jobs
    e.g. popular places job
    class PopularPlacesJob(args: Args) extends AccessLogJob(args) {

        implicit val mapMonoid = new MapMonoid[String, Long]()
        val ord = implicitly[Ordering[(Long, String)]].reverse

        readParseFilter()
            .flatMap(’entry -> ’ppid) {
                entry:AccessLogEntry => entry.request.ppid
            }
            .mapTo((’entry, ’ppid) -> (’ppid, ’time, ’app)) {
                arg: (AccessLogEntry, String) => (arg._2, arg._1.dateTime, a
            }
            .groupBy((’ppid, ’app)) {
                _.min(’time -> ’minTime)
                 .max(’time -> ’maxTime)
                 .size(’num)
            }
            .groupBy((’ppid)) {
                _.min(’minTime)
                 .max(’maxTime)
                 .sum(’num)
Not so good in Scala




       Almost whole team needed to learn the new language - luckily we have
       Toralf ;)
       Tools are not as mature as those in Java (but they are getting better very
       fast)
       Longer compilation, compiler has a lot more to do (e.g. type inference)
       Multiple inheritance (traits)
       Operators
       changes in every language release
What we have learned, discovered?




       When done right - it’s possible to painlessly migrate code to new
       language, developing new feautres in the same time
       How to use good typesystem and enjoy it
       Take advantage form whole great immutable world of painless
       programming
       Use functions as first class citizens of language
Plans




        Scala 2.10
        Run Transformations in Futures, Validations etc.
        Akka actors, Futures composition
        Kill last Java files?
        Stop using Spring
Thank you!




       project site:
       places.nlp.nokia.com
       My contact:
       lukasz.balamut@nokia.com
       @lbalamut
       open position in our team:

More Related Content

What's hot

Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越Caoyuan Deng
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
Bert Van Vreckem
 
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Sanjeev_Knoldus
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scripting
michid
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
Tim Underwood
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
Derek Chen-Becker
 
Scalaz
ScalazScalaz
Scalaz
mpilquist
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
fanf42
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
BTI360
 
Scala introduction
Scala introductionScala introduction
Scala introduction
Yardena Meymann
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Yardena Meymann
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and ClosuresSandip Kumar
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
Jonas Bonér
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala
Ostap Andrusiv
 
Scala Intro
Scala IntroScala Intro
Scala Intro
Paolo Platter
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
vito jeng
 

What's hot (19)

Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
Scala traits training by Sanjeev Kumar @Kick Start Scala traits & Play, organ...
 
Scala for scripting
Scala for scriptingScala for scripting
Scala for scripting
 
A Brief Intro to Scala
A Brief Intro to ScalaA Brief Intro to Scala
A Brief Intro to Scala
 
Stepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to ScalaStepping Up : A Brief Intro to Scala
Stepping Up : A Brief Intro to Scala
 
Scala
ScalaScala
Scala
 
Scalaz
ScalazScalaz
Scalaz
 
A Tour Of Scala
A Tour Of ScalaA Tour Of Scala
A Tour Of Scala
 
Scala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 WorldScala vs Java 8 in a Java 8 World
Scala vs Java 8 in a Java 8 World
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
 
Scaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with ScalaScaladroids: Developing Android Apps with Scala
Scaladroids: Developing Android Apps with Scala
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
 
Scala Intro
Scala IntroScala Intro
Scala Intro
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
 

Viewers also liked

Chakarawet1
Chakarawet1Chakarawet1
Towards a three-step laser excitation of rubidium Rydberg states for use in a...
Towards a three-step laser excitation of rubidium Rydberg states for use in a...Towards a three-step laser excitation of rubidium Rydberg states for use in a...
Towards a three-step laser excitation of rubidium Rydberg states for use in a...
Ben Catchpole
 
Bacteria LENRs-and isotopic shifts in Uranium-Larsen-Lattice Energy Dec 7 2010
Bacteria LENRs-and isotopic shifts in Uranium-Larsen-Lattice Energy Dec 7 2010Bacteria LENRs-and isotopic shifts in Uranium-Larsen-Lattice Energy Dec 7 2010
Bacteria LENRs-and isotopic shifts in Uranium-Larsen-Lattice Energy Dec 7 2010
Lewis Larsen
 
IB Chemistry on HNMR Spectroscopy and Spin spin coupling
IB Chemistry on HNMR Spectroscopy and Spin spin couplingIB Chemistry on HNMR Spectroscopy and Spin spin coupling
IB Chemistry on HNMR Spectroscopy and Spin spin coupling
Lawrence kok
 
IB Chemistry on Infrared Spectroscopy
IB Chemistry on Infrared SpectroscopyIB Chemistry on Infrared Spectroscopy
IB Chemistry on Infrared Spectroscopy
Lawrence kok
 
Nuclear Magnetic Resonance Spectroscopy
Nuclear Magnetic Resonance SpectroscopyNuclear Magnetic Resonance Spectroscopy
Nuclear Magnetic Resonance Spectroscopy
Assistant Professor in Chemistry
 
Hydrogen And Fuel Cell Technology For A Sustainable Future
Hydrogen And Fuel Cell Technology For A Sustainable FutureHydrogen And Fuel Cell Technology For A Sustainable Future
Hydrogen And Fuel Cell Technology For A Sustainable Future
Gavin Harper
 
NMR (nuclear Magnetic Resonance)
NMR (nuclear Magnetic Resonance)NMR (nuclear Magnetic Resonance)
NMR (nuclear Magnetic Resonance)
Rawat DA Greatt
 

Viewers also liked (8)

Chakarawet1
Chakarawet1Chakarawet1
Chakarawet1
 
Towards a three-step laser excitation of rubidium Rydberg states for use in a...
Towards a three-step laser excitation of rubidium Rydberg states for use in a...Towards a three-step laser excitation of rubidium Rydberg states for use in a...
Towards a three-step laser excitation of rubidium Rydberg states for use in a...
 
Bacteria LENRs-and isotopic shifts in Uranium-Larsen-Lattice Energy Dec 7 2010
Bacteria LENRs-and isotopic shifts in Uranium-Larsen-Lattice Energy Dec 7 2010Bacteria LENRs-and isotopic shifts in Uranium-Larsen-Lattice Energy Dec 7 2010
Bacteria LENRs-and isotopic shifts in Uranium-Larsen-Lattice Energy Dec 7 2010
 
IB Chemistry on HNMR Spectroscopy and Spin spin coupling
IB Chemistry on HNMR Spectroscopy and Spin spin couplingIB Chemistry on HNMR Spectroscopy and Spin spin coupling
IB Chemistry on HNMR Spectroscopy and Spin spin coupling
 
IB Chemistry on Infrared Spectroscopy
IB Chemistry on Infrared SpectroscopyIB Chemistry on Infrared Spectroscopy
IB Chemistry on Infrared Spectroscopy
 
Nuclear Magnetic Resonance Spectroscopy
Nuclear Magnetic Resonance SpectroscopyNuclear Magnetic Resonance Spectroscopy
Nuclear Magnetic Resonance Spectroscopy
 
Hydrogen And Fuel Cell Technology For A Sustainable Future
Hydrogen And Fuel Cell Technology For A Sustainable FutureHydrogen And Fuel Cell Technology For A Sustainable Future
Hydrogen And Fuel Cell Technology For A Sustainable Future
 
NMR (nuclear Magnetic Resonance)
NMR (nuclear Magnetic Resonance)NMR (nuclear Magnetic Resonance)
NMR (nuclear Magnetic Resonance)
 

Similar to Scala in Places API

(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
league
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scalashinolajla
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
Stuart Roebuck
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
Jesper Kamstrup Linnet
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
Hugo Gävert
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
Jesper Kamstrup Linnet
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
Venkateswaran Kandasamy
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
Isaias Barroso
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersMiles Sabin
 
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
Miles Sabin
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
Sandeep Kr. Singh
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfHiroshi Ono
 
Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and Profit
Tomer Gabel
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
Peter Maas
 

Similar to Scala in Places API (20)

(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
The Scala Programming Language
The Scala Programming LanguageThe Scala Programming Language
The Scala Programming Language
 
Taxonomy of Scala
Taxonomy of ScalaTaxonomy of Scala
Taxonomy of Scala
 
Scala @ TechMeetup Edinburgh
Scala @ TechMeetup EdinburghScala @ TechMeetup Edinburgh
Scala @ TechMeetup Edinburgh
 
Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?Scala - en bedre og mere effektiv Java?
Scala - en bedre og mere effektiv Java?
 
Introduction to Scalding and Monoids
Introduction to Scalding and MonoidsIntroduction to Scalding and Monoids
Introduction to Scalding and Monoids
 
Scala - en bedre Java?
Scala - en bedre Java?Scala - en bedre Java?
Scala - en bedre Java?
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
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
 
What is new in Java 8
What is new in Java 8What is new in Java 8
What is new in Java 8
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
 
Scala Refactoring for Fun and Profit
Scala Refactoring for Fun and ProfitScala Refactoring for Fun and Profit
Scala Refactoring for Fun and Profit
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 

Recently uploaded

From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
Product School
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
Safe Software
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Product School
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Tobias Schneck
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
Elena Simperl
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
Abida Shariff
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
DianaGray10
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
Ralf Eggert
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
DianaGray10
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
Guy Korland
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
Paul Groth
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
Thijs Feryn
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
RTTS
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Product School
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
BookNet Canada
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 

Recently uploaded (20)

From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
From Daily Decisions to Bottom Line: Connecting Product Work to Revenue by VP...
 
Essentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with ParametersEssentials of Automations: Optimizing FME Workflows with Parameters
Essentials of Automations: Optimizing FME Workflows with Parameters
 
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
Unsubscribed: Combat Subscription Fatigue With a Membership Mentality by Head...
 
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdfFIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
FIDO Alliance Osaka Seminar: Passkeys and the Road Ahead.pdf
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
Kubernetes & AI - Beauty and the Beast !?! @KCD Istanbul 2024
 
Knowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and backKnowledge engineering: from people to machines and back
Knowledge engineering: from people to machines and back
 
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptxIOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
IOS-PENTESTING-BEGINNERS-PRACTICAL-GUIDE-.pptx
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4UiPath Test Automation using UiPath Test Suite series, part 4
UiPath Test Automation using UiPath Test Suite series, part 4
 
PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)PHP Frameworks: I want to break free (IPC Berlin 2024)
PHP Frameworks: I want to break free (IPC Berlin 2024)
 
UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3UiPath Test Automation using UiPath Test Suite series, part 3
UiPath Test Automation using UiPath Test Suite series, part 3
 
GraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge GraphGraphRAG is All You need? LLM & Knowledge Graph
GraphRAG is All You need? LLM & Knowledge Graph
 
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMsTo Graph or Not to Graph Knowledge Graph Architectures and LLMs
To Graph or Not to Graph Knowledge Graph Architectures and LLMs
 
Accelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish CachingAccelerate your Kubernetes clusters with Varnish Caching
Accelerate your Kubernetes clusters with Varnish Caching
 
JMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and GrafanaJMeter webinar - integration with InfluxDB and Grafana
JMeter webinar - integration with InfluxDB and Grafana
 
Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...Mission to Decommission: Importance of Decommissioning Products to Increase E...
Mission to Decommission: Importance of Decommissioning Products to Increase E...
 
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...Transcript: Selling digital books in 2024: Insights from industry leaders - T...
Transcript: Selling digital books in 2024: Insights from industry leaders - T...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 

Scala in Places API

  • 1. Scala in Nokia Places API Lukasz Balamut - Places API Team 17 April 2013
  • 2. Purpose of this talk Why are we spending time migrating to a new language? How are we doing that? What have we learned? and of course: we are hiring.
  • 3. Our scala story. Our migration in lines of code We’ve discovered more and more things on the way.
  • 4. The Concordion tests problem In June 2011 we had problems with Concordion (HTML based acceptance test framework), hard to integrate HTML tests were not readable Solution: Multi-line Strings in Scala Continue using JUnit val expectedBody = """ { "id":"250u09wh-83d4c5479b7c4db9836602936dbc8cb8", "title" : "Marfil (Le)", "alternativeNames" : [ { "name" : "Le Marfil", "language" : "fr" } ] } """
  • 5. The test names problem JUnit + camel case - not that readable for long names @Test def preservesSearchResponseItemOrder() { /* ... */ } JUnit + underscores - violates naming convention, but better to read @Test def preserves_search_response_item_order() { /* ... */ } ScalaTest test("preserves search response’s item order") { /* ... */ } It is supported by tools we use and produces nice output when run (as a bonus) [info] DiscoverAroundAcceptanceTest: [info] - calls nsp with 15Km radius [info] - preserves search response’s item order [info] - when requesting zero results, no request to search is made
  • 6. Lift-Json JSON (de)serialisation can be done in really nice way e.g. getting place id: { "place": { "a_id": "276u33db-6f084959f97c45bc9db26348bafd4563" } } Also there is a generic way of parsing json, that gives you XPath like access: val id = (json "place" "a_id").extract[String] Lift-json provides also easy and efficient case class JSON (de)serialisation, hance case classes
  • 7. Scala case classes in the model We model our upstream and downstream datamodels as case classes. case class Place ( name: String, placeId: PlaceID //(...) ) Each case class is a proper immutable data type - the new Java Bean ;), A lot of boilerplate code is generated by the compiler e.g.: accessors, equals/hashCode, copy methods, toString apply/unapply (for pattern maching), After decompiling the scala code above we will end up with 191 lines of Java: package pbapi.model.api; import scala.*; import scala.collection.Iterator; import scala.runtime.BoxesRunTime; import scala.runtime.ScalaRunTime$;
  • 8. Scala case classes - Configuration Easy to update configuration Easy to compare environments’ configuration case class HttpClientConfig( serviceName: String, serviceBaseUrl: URL, readTimeout: Int = 0, connectionTimeout: Int, proxy: Option[ProxyConfig] = None, oauthKeys: Option[OAuthConfig] = None, displayUrl: Option[String] = None ) "httpConfig":{ "serviceName":"recommendations", "serviceBaseUrl":"http://nose.svc.ovi.com/rest/v1/recommendations/near "readTimeout":4000, "connectionTimeout":500, "displayUrl":"http://nose.svc.ovi.com/rest/v1/recommendations/nearby/" }
  • 9. The Scala Type System A great way to express assumptions Have them checked by the compiler through the whole codebase At every point in the code know what to expect or you will be reminded by compiler.
  • 10. The Scala Type System - Options 1 Avoid null references (see The Billion Dollar Mistake ) This will not compile! case class UpstreamResponse ( unreliableField: Option[String] ) case class MyResponse ( reliableField: String ) def transform(upstream: UpstreamResponse) = MyResponse( reliableField = upstream.unreliableField //<-- incompatible type )
  • 11. The Scala Type System - Options 2 But this will: case class UpstreamResponse ( unreliableField: Option[String] ) case class MyResponse ( reliableField: String ) def transform(upstream: UpstreamResponse) = MyResponse( reliableField = upstream.unreliableField.getOrElse("n/a") // enf )
  • 12. The Scala Type System - Options 3 how we were learning e.g.: to transform string when it is defined def transform(str: String): String reliableField = if (upstream.unreliableField.isDefined) transform(upstream.unreliableField.get) else "n/a" reliableField = upstream.unreliableField match { case Some(f) => transform(f) case None => "n/a" } reliableField = upstream.unreliableField.map(transform) | "n/a"
  • 13. The Scala Type System - Standard Types Immutable Map, List, Sets val map: Map[String, String] = Map("a" -> "a", "b" -> "b") val list: List[String] = "a" :: "b" :: Nil Tuples to express Pairs, Triplets etc. val pair: Pair[String, Int] = ("a", 1) val (a, b) = pair // defines a:String and b:Int
  • 14. The Scala Type System - error handling Types can help with exceptional cases val parsed: Validation[NumberFormatException, Int] = someString.parseInt val optional: Option[Int] = parsed.toOption val withDefault: Int = optional.getOrElse(0) //if there was parsing prob Exception to Option val sub: Option[String] = allCatch.opt(line.substring(line.indexOf("{""))) or Either val parsed: Either[Throwable, Incident] = allCatch.either(new Incident(parse(jsonString)) and handle it later parsed match { case Right(j) => Some(j) case Left(t) => { println("Parse error %s".format(t.getMessage)) None
  • 15. The Scala Type System - functions we defer translation (Translated) and text rendering (FormattedText) to serialisation time using function composition so we don’t need to pass user context through the whole stack e.g.: case class Place ( //(...) attribution: Option[Translated[FormattedText]], //(...) ) case class Translated[A](translator: TransEnv => A) { def apply(env: TransEnv): A = translator(env) def map[B](f: A => B): Translated[B] = new Translated[B](env => f(apply(env))) //(...) }
  • 16. XML literals XML can be part of the code and compiler is checking syntax of it: def toKmlCoordinates(style: String): String = (<Placemark> <name>{"bbox " + this}</name> <styleUrl>{style}</styleUrl> <Polygon> <outerBoundaryIs> <LinearRing> <coordinates> {west + "," + north + ",0"} {east + "," + north + ",0"} {east + "," + south + ",0"} {west + "," + south + ",0"} {west + "," + north + ",0"} </coordinates> </LinearRing> </outerBoundaryIs> </Polygon> </Placemark>).toString
  • 17. Scalacheck Automatic testing of assumptions, using set of generated values. e.g. the code below tests if BBox.parse(a.toString) == a is true for any a val generator: Gen[BBox] = for { s <- choose(-90.0, 90.0) n <- choose(-90.0, 90.0) if (n > s) w <- choose(-180.0, 180.0) e <- choose(-180.0, 180.0) } yield new BBox(w, s, e, n) property("parse . toString is identity") { check { (a: BBox) => BBox.parse(a.toString) == a } } may yield this failing test message after several evaluations.
  • 18. Scala (Scalding) in our analytics jobs e.g. popular places job class PopularPlacesJob(args: Args) extends AccessLogJob(args) { implicit val mapMonoid = new MapMonoid[String, Long]() val ord = implicitly[Ordering[(Long, String)]].reverse readParseFilter() .flatMap(’entry -> ’ppid) { entry:AccessLogEntry => entry.request.ppid } .mapTo((’entry, ’ppid) -> (’ppid, ’time, ’app)) { arg: (AccessLogEntry, String) => (arg._2, arg._1.dateTime, a } .groupBy((’ppid, ’app)) { _.min(’time -> ’minTime) .max(’time -> ’maxTime) .size(’num) } .groupBy((’ppid)) { _.min(’minTime) .max(’maxTime) .sum(’num)
  • 19. Not so good in Scala Almost whole team needed to learn the new language - luckily we have Toralf ;) Tools are not as mature as those in Java (but they are getting better very fast) Longer compilation, compiler has a lot more to do (e.g. type inference) Multiple inheritance (traits) Operators changes in every language release
  • 20. What we have learned, discovered? When done right - it’s possible to painlessly migrate code to new language, developing new feautres in the same time How to use good typesystem and enjoy it Take advantage form whole great immutable world of painless programming Use functions as first class citizens of language
  • 21. Plans Scala 2.10 Run Transformations in Futures, Validations etc. Akka actors, Futures composition Kill last Java files? Stop using Spring
  • 22. Thank you! project site: places.nlp.nokia.com My contact: lukasz.balamut@nokia.com @lbalamut open position in our team: