Introduction to Scala - PowerPoint PPT Presentation

peri
introduction to scala n.
Skip this Video
Loading SlideShow in 5 Seconds..
Introduction to Scala PowerPoint Presentation
Download Presentation
Introduction to Scala

play fullscreen
1 / 58
Download Presentation
Introduction to Scala
165 Views
Download Presentation

Introduction to Scala

- - - - - - - - - - - - - - - - - - - - - - - - - - - E N D - - - - - - - - - - - - - - - - - - - - - - - - - - -
Presentation Transcript

  1. Introductionto Scala

  2. Briefhistory of programminglanguages 1801 - Joseph Marie Jacquard uses punch cards to instruct a loom to weave "hello, world" into a tapestry. Redditers of the time are not impressed due to the lack of tail call recursion, concurrency, or proper capitalization. 1940s - Various "computers" are "programmed" using direct wiring and switches. Engineers do this in order to avoid the tabs vs spaces debate. 1964 - John Kemeny and Thomas Kurtz create BASIC, an unstructured programming language for non-computer scientists. 1965 - Kemeny and Kurtz go to 1964. … 2003 – First Scala release Fromhttp://james-iry.blogspot.com/2009/05/brief-incomplete-and-mostly-wrong.html

  3. Introductionto Scala - Agenda • Intro • Controlstructures • Functions • Collections • OO • Implicits • Unit testing • Parting thoughts

  4. Current state of Scala • Modern language • OO and FP conceptsintegrated • Runon JVM (and soon .NET) • By Martin Odersky (EPFL) • Generic Java ( => genericsinJava 1.5) • Java compilerimplementation (Java 1.3) • FOSS • Scala License ~ 3-clause BSD license • Commercialsupportavailable (TypeSafe)

  5. Hands-onexperience • Compiledlang, butwecanuse REPL • Read-Evaluate-Print-Loop, forexperimenting • Execute: scala, or go tohttp://www.simplyscala.com/ • Formatting

  6. Powerfultypesystem • Compile-timestatictypechecking • Local typeinference

  7. Variables and values • var and val • Mutablevsimmutable • var x = 5 variable, mutablereferenceto x • val x = 4 value, immutablereferenceto x • LikefinalsomeType xin Java • Reference is immutable, butnotnecessarytheobject • May optionallyspecifytype • val x: String = „hello” • Compilerinfersitforusanyway • Nicetospecifytypeexplicitlyforpublic API

  8. Controlstructures fromhttp://xkcd.com/292/

  9. Controlstructures – Sequence and branching • Controlstructuresasfunctions • Sequence • laststatement (of block) is theresult of theblock • Branching • branchtaken is theresult

  10. Controlstructures – Patternmatching • Patternmatching (briefly) • Can be simple, Scala’s switch • Or more comprehensive (structuralunification) no fall-through betweencases guardexpression free variables defaultcase

  11. Controlstructures – Loops • Whileloop • Resultis Unit (Scala’s void) • Forloop • Swissarmyknife, butcan be assimpleas

  12. For looprevisited • Forloop • Cancontain 3 kind of clauses • Generators i <- something • Conditionsif i == 5 • Definitions a = i * 2 Clausescan be onseparatelines ifincurlybraces

  13. For looprevisited • Forloop • Ordering and composition of clausesnotrestricted • Generatorspattern-match • Silentlyskipifmatchfails! pattern Note: thesearetuples

  14. For looprevisited • Forloop (comprehension) • Can: • Justdosomeside-effect • Orcreate a collection (yield) • Underthehood • Forcomprehension is syntacticsugar • Expandstomap, withFilter, foreach yield must come beforethefor body

  15. Quiz • Controlstructurequiz • Inputs • dest = List(„HU”, „SP”) • hotelByCountry = Map(„SP” -> 100, „FR” -> 80, „HU” -> 20) • Help • The result of someMap(key) is therespectivevalue • Output • Sum number of hotels • Examplesolution • var s = 0 • for (c <- dest) s += hotelByCountry(c) • s

  16. Functions and methods • Method • Definedby a class/object • Shorthand argument is val bydefault, can’t change No needforblockforsingleexpression • Returntypeinferred • Stillnicetoexplicitlywriteitforpublic API

  17. Functions and methods • Function • Objectbyitself • Has type • FunctionN[-ArgT1, -ArgT2, …, -ArgTN, +ResT] • (ArgT1, ArgT2, …, ArgTN) => ResT • Can be passedasparameter, etc. • Idealforcallbacks, etc. • No needforsingle-methodclassboilerplate Type of value Argumentlist Returnvalue May omittype asusual

  18. Functions and methods • Arglessmethods Parenlessmethod is calledwithoutparens Don’t mind.. Bottom line is, can’t doit Methodwithparenmay be calledeitherway, butgoodpracticetosticktocallingwithparens.

  19. Functions and methods • Arglessfuns f is a value, containingafunctiontaking no args, returningBoolean So f is thefunctionitself Applyingthefunction

  20. Functions and methods • Procedure • Not a thirdkind, justnaming • Can be methodorfunction • Returntype Unit • Onlyvalue is (), anythingcan be convertedtoit => no needtowriteexplicitly • Calledforitsside-effect No returntypeorequalssign

  21. Functions and methods • Methodcallwithnamedargs • Defaultargumentvalues

  22. Quiz • Functionquiz • Inputs • valhasFreeRoom = (c: String) => (c == „HU”) • vallocations = „ES” :: „HU” :: „FR” :: Nil • Write a funtakingafunctionpredasarg • val filter = (cs: List[String], pred: ???) => ??? • filter(location, hasFreeRooms) shouldreturn „HU” :: Nil • Examplesolution • val filter = (cs: List[String], pred: (String) => Boolean) => for (c <- csifpred(c)) yieldc Functiontypedeliberatelyomittedforquiz

  23. Iterators fromhttp://xkcd.com/571/

  24. Collections • Mutable and immutable • Packages: • scala.collection (this has thecommoninterface) • scala.collection.{mutable, immutable} • Modifyopsonimmutablecollectionsresultinnewcollection • Quiteeffective, notcopy-all • Whyimmutable? • No needto be defensive • No concurrencyissues • Whymutable? • May be easier for someproblems • Possiblybetter performance Scala philosophy: Ifpossible, haveimmutableinterface, and speedupinternalswithmutable solution.

  25. Collections • Hierarchy (subset) • Traversable • Iterable • Seq • IndexedSeq (Vector, WrappedArray) • LinearSeq(List) • Buffer (ArrayBuffer, ListBuffer) • Set (HashSet, BitSet, SortedSet, …) • Map (HashMap, SortedMap, …) Canapplyoperationeffectivelyforallelementsinone go Has iteratorwithhasNext / next Fast random access Fastlinearaccess Italicstyle: mutabletype Boldstyle: immutabletype

  26. Collections • Creatingcollections • scala.collection.immutable._ is importedbydefault • Cancreate a defaultimplementationusingjustthetypename • Why? Seein OO part. • Why is itgood? • The shorthandformchooses an appropriateimplementationforus • Inthiscase, a specialtype for 1-element maps (efficient) Ah! It’s a HashMap! WTH?

  27. Collections • Type & syntaxremarks • Lists • Tuples EyecandyforTupleX Alternatesyntaxfor Tuple2

  28. Collections • Rich and unifiedcollectioninterface • methods of collectionclasses • map, filter, foreach, … • Let’s stop here for a moment. This is veryuseful, but a bit manytotype c.map(f): applies a function f toallelements of collection c, yieldsnewcollection Dotlessmethodcall Curlybraceinsteadparen* Letinferencerguessargtype Shorthandsyntaxforanonymousfun *: matter of taste

  29. Collections • Rich and unifiedcollectioninterface • Instead of map, filter, … returntypealways being Iterable • Resulttype is keptasclosetooriginalaspossible Result is map Result is Iterable

  30. Collections • Rich and unifiedcollectioninterface • map, filter … and other 20 – 30 usefulmethods • No needto roll yourown, canspare a lot of time • Easytoachievecomplextaskusingcomposingthesefunctionality

  31. Quiz • Collectionquiz • Inputs • dest = List(„HU”, „SP”) • hotelByCountry = Map(„SP” -> 100, „FR” -> 80, „HU” -> 20) • Help • Usethe map as a function, then sum • Output • Sum number of hotels • Examplesolutions • dest map hotelByCountry sum • (for (d <- dest) yieldhotelByCountry(d)) sum

  32. OO • Classes • Syntax • Primaryconstructorasclassarguments • Body notmandatory • Argument / member / fieldmodifiers: • No modifier ~ valwithprivate[this] visibility, noaccessors (ctoronly) • val/var ~ publicvisibility • private, private[…], protected, protected[…] • Note: Scala’s protected is not Java’s packageprotected

  33. OO • Uniform Access • Insteadhiddenval/var + getter/setter • Canjustexposetheval/var • And ifneededlater • hideval/var • defineaccessormethods

  34. OO • Singleinheritance • Abstractmethod and class • Methodoverriding

  35. OO • Traitasinterface Notsonice, boilerplate Butthis is alsopossible: Whyworks? Canoverridearglessdefwith a val (nototherwayaround)

  36. OO • Traitashelper mixin • Either for privateorpublicuse • Addsfunctionality, butdoesnotmodifies Abstractfield, needsto be specifiedwhen mixed in Addedfunctionality Mix itin And use

  37. OO • Traitself-type • Specifiesthetypethetraitneedsto be mixed into „Thistrait must be mixed into a Reservable” UseReservablefunctionality

  38. OO • Traitasstackablemodification Whynotself-type? BecausePoliteWisher is-a Wisher Linearizationdetermines stackingorder

  39. OO • Singletons • objectinstead of class • Samenameasclass/trait => „companionobject” • Frequently, companionasfactory

  40. OO • Caseclasses • Ctorargsbecomeval’s automatically, constructioncanomitnew Singletoncases, enum-like Exampleusage

  41. OO • Caseclasses • Generatedequals, hashCode, copy • Supportseasypatternmatching • Best ifimmutable, no subclasses copycreates newobjectwith altered state Couldinvertcaseorder togive Hungary a leverage

  42. Handlingnulls • Optiontype • empty/1-element collection, instead of null/value • Chaining, patternmatching • Cases: NoneorSome(x) • Commonoperations: isDefined, getOrElse, orElse, map, flatMap Note! orElsetakes a val (calculatedonlyonce), Soinonerunweeitheralwayslieornot

  43. Implicit conversion • Implicits • Let’s magichappen • Valuedefinedas implicit getspassedtoimplicitargument Implicit argument Btw, methodscanhave multipleargumentlists (currying, implicits, inference)

  44. Implicit conversion • Implicits • Compilertries implicit conversionsonfailedmethodresolution

  45. Implicit conversion • Implicits • Conversionusingsrc/dsttype’s companion

  46. Implicit conversion • Implicits • The compiler • won’t chainimplicits (1-step max) • won’t use implicit if more thanoneinscope… • …unlessit is notambigous: • Willuse implicit definedinnearestsubclass • Willuse more special implicit (like Java’s overloadresolution) • Famousimplicits: • Manyinscala.Predef • scala.collection.JavaConversion._ Don’t overuseimplicits! And alwaysrestricttheirscope.

  47. Unit testing • ScalaTest • Onepossiblechoice • Otherfamous: specs(2) • Specsrunstestsinisolation • ScalaTestrunsspec „asreadbyuser” sequentially, withoutisolation • ManySpecstylessupported • FlatSpec, WordSpec, FeatureSpec, … • Thesedifferin test organizationonly • Tests („Specs”) can be readas unit specification • Can mix inmatchers, informativeelements • ShouldMatchers • Given-When-Then • Interop • CanrunviaJUnitrunner • Can test Java classes

  48. ScalaTest - FlatSpec

  49. ScalaTest - FeatureSpec • First a roughoutline

  50. ScalaTest - FeatureSpec Refinements