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:
Ad

More Related Content

What's hot (19)

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
 
Scala
ScalaScala
Scala
Sven Efftinge
 
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 2008
Yardena Meymann
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip 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
 
Scala on Android
Scala on AndroidScala on Android
Scala on Android
Jakub Kahovec
 
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
 
1.2 scala basics
1.2 scala basics1.2 scala basics
1.2 scala basics
futurespective
 
Scala Intro
Scala IntroScala Intro
Scala Intro
Paolo Platter
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
vito jeng
 
Scala-对Java的修正和超越
Scala-对Java的修正和超越Scala-对Java的修正和超越
Scala-对Java的修正和超越
Caoyuan Deng
 
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
 
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 at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008Scala at HUJI PL Seminar 2008
Scala at HUJI PL Seminar 2008
Yardena Meymann
 
Functional Objects & Function and Closures
Functional Objects  & Function and ClosuresFunctional Objects  & Function and Closures
Functional Objects & Function and Closures
Sandip 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
 
JavaScript Web Development
JavaScript Web DevelopmentJavaScript Web Development
JavaScript Web Development
vito jeng
 

Viewers also liked (8)

Chakarawet1
Chakarawet1Chakarawet1
Chakarawet1
Khetpakorn Chakarawet
 
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
 
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
 
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
 
Ad

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?
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 Scala
shinolajla
 
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 for curious
Scala for curiousScala for curious
Scala for curious
Tim (dev-tim) Zadorozhniy
 
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
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
Raúl Raja Martínez
 
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
Miles 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.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi 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
 
(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 Scala
shinolajla
 
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 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 Developers
Miles 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
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi Ono
 
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdfpragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
pragmaticrealworldscalajfokus2009-1233251076441384-2.pdf
Hiroshi 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
 
Ad

Recently uploaded (20)

tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
tecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdftecnologias de las primeras civilizaciones.pdf
tecnologias de las primeras civilizaciones.pdf
fjgm517
 
Cybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure ADCybersecurity Identity and Access Solutions using Azure AD
Cybersecurity Identity and Access Solutions using Azure AD
VICTOR MAESTRE RAMIREZ
 
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdfSAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
SAP Modernization: Maximizing the Value of Your SAP S/4HANA Migration.pdf
Precisely
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Big Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur MorganBig Data Analytics Quick Research Guide by Arthur Morgan
Big Data Analytics Quick Research Guide by Arthur Morgan
Arthur Morgan
 
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdfThe Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
The Evolution of Meme Coins A New Era for Digital Currency ppt.pdf
Abi john
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes Partner Innovation Updates for May 2025
ThousandEyes
 
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath MaestroDev Dives: Automate and orchestrate your processes with UiPath Maestro
Dev Dives: Automate and orchestrate your processes with UiPath Maestro
UiPathCommunity
 
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager APIUiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPath Community Berlin: Orchestrator API, Swagger, and Test Manager API
UiPathCommunity
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
Linux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdfLinux Professional Institute LPIC-1 Exam.pdf
Linux Professional Institute LPIC-1 Exam.pdf
RHCSA Guru
 
Mobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi ArabiaMobile App Development Company in Saudi Arabia
Mobile App Development Company in Saudi Arabia
Steve Jonas
 
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Massive Power Outage Hits Spain, Portugal, and France: Causes, Impact, and On...
Aqusag Technologies
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
IEDM 2024 Tutorial2_Advances in CMOS Technologies and Future Directions for C...
organizerofv
 
Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.Greenhouse_Monitoring_Presentation.pptx.
Greenhouse_Monitoring_Presentation.pptx.
hpbmnnxrvb
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
AI Changes Everything – Talk at Cardiff Metropolitan University, 29th April 2...
Alan Dix
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 

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: [email protected] @lbalamut open position in our team: