770 likes | 1.14k Views
Introduction to Scala. Brief history of programming languages. 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.
E N D
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
Introductionto Scala - Agenda • Intro • Controlstructures • Functions • Collections • OO • Implicits • Unit testing • Parting thoughts
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)
Hands-onexperience • Compiledlang, butwecanuse REPL • Read-Evaluate-Print-Loop, forexperimenting • Execute: scala, or go tohttp://www.simplyscala.com/ • Formatting
Powerfultypesystem • Compile-timestatictypechecking • Local typeinference
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
Controlstructures fromhttp://xkcd.com/292/
Controlstructures – Sequence and branching • Controlstructuresasfunctions • Sequence • laststatement (of block) is theresult of theblock • Branching • branchtaken is theresult
Controlstructures – Patternmatching • Patternmatching (briefly) • Can be simple, Scala’s switch • Or more comprehensive (structuralunification) no fall-through betweencases guardexpression free variables defaultcase
Controlstructures – Loops • Whileloop • Resultis Unit (Scala’s void) • Forloop • Swissarmyknife, butcan be assimpleas
For looprevisited • Forloop • Cancontain 3 kind of clauses • Generators i <- something • Conditionsif i == 5 • Definitions a = i * 2 Clausescan be onseparatelines ifincurlybraces
For looprevisited • Forloop • Ordering and composition of clausesnotrestricted • Generatorspattern-match • Silentlyskipifmatchfails! pattern Note: thesearetuples
For looprevisited • Forloop (comprehension) • Can: • Justdosomeside-effect • Orcreate a collection (yield) • Underthehood • Forcomprehension is syntacticsugar • Expandstomap, withFilter, foreach yield must come beforethefor body
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
Functions and methods • Method • Definedby a class/object • Shorthand argument is val bydefault, can’t change No needforblockforsingleexpression • Returntypeinferred • Stillnicetoexplicitlywriteitforpublic API
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
Functions and methods • Arglessmethods Parenlessmethod is calledwithoutparens Don’t mind.. Bottom line is, can’t doit Methodwithparenmay be calledeitherway, butgoodpracticetosticktocallingwithparens.
Functions and methods • Arglessfuns f is a value, containingafunctiontaking no args, returningBoolean So f is thefunctionitself Applyingthefunction
Functions and methods • Procedure • Not a thirdkind, justnaming • Can be methodorfunction • Returntype Unit • Onlyvalue is (), anythingcan be convertedtoit => no needtowriteexplicitly • Calledforitsside-effect No returntypeorequalssign
Functions and methods • Methodcallwithnamedargs • Defaultargumentvalues
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
Iterators fromhttp://xkcd.com/571/
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.
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
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?
Collections • Type & syntaxremarks • Lists • Tuples EyecandyforTupleX Alternatesyntaxfor Tuple2
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
Collections • Rich and unifiedcollectioninterface • Instead of map, filter, … returntypealways being Iterable • Resulttype is keptasclosetooriginalaspossible Result is map Result is Iterable
Collections • Rich and unifiedcollectioninterface • map, filter … and other 20 – 30 usefulmethods • No needto roll yourown, canspare a lot of time • Easytoachievecomplextaskusingcomposingthesefunctionality
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
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
OO • Uniform Access • Insteadhiddenval/var + getter/setter • Canjustexposetheval/var • And ifneededlater • hideval/var • defineaccessormethods
OO • Singleinheritance • Abstractmethod and class • Methodoverriding
OO • Traitasinterface Notsonice, boilerplate Butthis is alsopossible: Whyworks? Canoverridearglessdefwith a val (nototherwayaround)
OO • Traitashelper mixin • Either for privateorpublicuse • Addsfunctionality, butdoesnotmodifies Abstractfield, needsto be specifiedwhen mixed in Addedfunctionality Mix itin And use
OO • Traitself-type • Specifiesthetypethetraitneedsto be mixed into „Thistrait must be mixed into a Reservable” UseReservablefunctionality
OO • Traitasstackablemodification Whynotself-type? BecausePoliteWisher is-a Wisher Linearizationdetermines stackingorder
OO • Singletons • objectinstead of class • Samenameasclass/trait => „companionobject” • Frequently, companionasfactory
OO • Caseclasses • Ctorargsbecomeval’s automatically, constructioncanomitnew Singletoncases, enum-like Exampleusage
OO • Caseclasses • Generatedequals, hashCode, copy • Supportseasypatternmatching • Best ifimmutable, no subclasses copycreates newobjectwith altered state Couldinvertcaseorder togive Hungary a leverage
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
Implicit conversion • Implicits • Let’s magichappen • Valuedefinedas implicit getspassedtoimplicitargument Implicit argument Btw, methodscanhave multipleargumentlists (currying, implicits, inference)
Implicit conversion • Implicits • Compilertries implicit conversionsonfailedmethodresolution
Implicit conversion • Implicits • Conversionusingsrc/dsttype’s companion
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.
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
ScalaTest - FeatureSpec • First a roughoutline
ScalaTest - FeatureSpec Refinements