SlideShare a Scribd company logo
1 of 66
Scala František Kocun
“I can honestly say if someone had shown me the Programming in Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy.“ JamesStrachan, Groovy creator
“No other language on the JVM seems as capable of being a "replacement for Java" as Scala, and the momentum behind Scala is now unquestionable.“ CharlesNutter, JRubycoredeveloper
“Scala.“ JamesGosling, Java creator Answer on a question, which language would he use now on JVM except Java.
“On my radar, the current best exit strategy for Java is Scala.„ BruceEckel,author of many books
Scala vs Java Scala removes break, continue, goto static primitive types raw types (every type parameter „generics“ has to be stated) operators (all are methods) override is not more optional 	(when overriding in Scala one has to declare override)
Scala vs Ruby and Groovy Scala has two type of fans Java programmers (pros of functional programming) Ruby programmers (pros of language with static typing) Implicits, structural typing and type inference, resembles work with language with dynamic typing Scala is compiles a compiled language and all types are checked in compilation time one can not call a non existing method no ClassCastException in runtime possibility to refactor as fast as Java
Scala unifies FP and OOP
Why to unify FP and OOP Both approaches are complementary Functional Object-oriented Abstraction Functions Higher-order functions Parametric  	polymorphism Extending, state dependent behavior Inheritance Polymorphism Encapsulation Dynamic configuration
Where? Manipulation of data structures  collections, trees, ADTs, ... Internal/External DSLs OSGi, Apache Camel, scala-query,  	specs, built-in parser Modular applications Mixins, dependency injection, DCI (data, context & interaction)
How? ,[object Object]
Pattern matching, case classes
Parametric polymorphism
Traits
Higher-order functions
Function as output argument
ImplicitsManipulation of data structures  collections, trees, ADTs, ... Internal/External DSLs OSGi, Apache Camel, scala-query,  	specs, built-in parser Modular applications Mixins, dependency injection, DCI (data, context & interaction)
Function as value Manipulation of data structures Collections Trees DSL
Example - filtering Java public Collection<Ticket> approved(Collection<Ticket> tickets){ 	Collection<Ticket> result = new ArrayList<Ticket>(); for(Ticket ticket : tickets){ if(ticket.getState() == State.APPROVED) result.add(icket); 	} return result; }
Example - filtering Java publicCollection<Ticket> approved(Collection<Ticket> tickets){ Collection<Ticket> result = new ArrayList<Ticket>(); for(Ticketticket: tickets){ filter if(ticket.getState()== State.APPROVED) result.add(ticket); } returnresult; } With what? What to do? How?
Yes, it can be done in Java Interface for conditon ... and the use Filter util method publicinterfaceICondition<T> { publicbooleancheck(T toBeChecked); } publicstatic <T> Collection<T> filter(Collection<T> ts, ICondition<T> c){ Collection<T> result = new ArrayList<T>(); for(T t : ts) if(c.check(t)) result.add(t); returnresult; } CollestionUtils.filter(verzie, new ICondition<Ticket>() { 	public boolean check(TickettoBeChecked) 	{ 		return toBeChecked.getState() == State.APPROVED; 	} });
Example - filtering Scala defapproved(tickets: List[Ticket]) { 	tickets filter (_.getState() == State.APPROVED)   }
WTF ? What type has the parameter in the function „filter“? List[+A]{ deffilter (p : (A) => Boolean) : List[A]  } Java : (A) => Boolean public interface Function1<O, I> { 	O apply(I input); } interface ICondition<I> extends IFunction1<Boolean, I> {}
Scala List count (p : (A) => Boolean) :Int exists (p : (A) => Boolean) : Boolean filter (p : (A) => Boolean) : List[A]  find (p : (A) => Boolean) : Option[A]  foldLeft [B](z : B)(f : (B, A) => B) : B forall (p : (A) => Boolean) : Boolean foreach (f : (A) => Unit) : Unit map [B](f : (A) => B) : List[B]  remove (p : (A) => Boolean) : List[A]
Scala List Most of them is inherited from trait Iterable. So every collection, array has them, because they inherit from Iterable. Similar functions can be written for trees. count (p : (A) => Boolean) :Int exists (p : (A) => Boolean) : Boolean filter (p : (A) => Boolean) : List[A]  find (p : (A) => Boolean) : Option[A]  foldLeft [B](z : B)(f : (B, A) => B) : B forall (p : (A) => Boolean) : Boolean foreach (f : (A) => Unit) : Unit map [B](f : (A) => B) : List[B]  remove (p : (A) => Boolean) : List[A]
Function can be assigned to variable varf : (String => Unit) = (x) => println(x) Function can be passed to another function tickets filter (t => t.getState() == State.APPROVED) Return value from function can be a function  defdeductKind = tax | insurance | retirement Function is primitive type, basic building block, with the same importance as an integer or a string. If functions takes another function as an argument or  if it returns a function, it is called a higher-order function.
Examples Numbers multiplied by two Employees to DTOs List(1, 2, 3, 4, 5) map { _ * 2 } > List[Int] = List(2, 4, 6, 8, 10) caseclassEmployee( varname : String) caseclass DTOEmployee( var name : String) deftoDto(e : Employee) = newDTOZamestnanec(z.meno) List(newEmployee(“John"),  newEmployee(“Jack"))  maptoDto > List[DTOEmployee] = List(DTOEmployee(John), DTOEmployee(Jack))
Type declaration In Scala types are written after colon exists (p : (A) => Boolean) : Boolean var age :Int= 24                              val age = 33 If type is unambiguous, it doesn’t have to be declared Return type of function exists Argument p is of type function from A to Boolean Type of variableage
ValvsVar ,[object Object],   (v Java it would be final) ,[object Object],valage:Int=22 age = 33 //ERROR ,[object Object]
 creates field, getter   and setter varage:Int=22 age = 33
List Operator :: is bound from right val list1 = List("Programming", "Scala")  val list2 = "People" :: "should" :: "read" :: list1 val list2 = ("People" :: ("should" :: ("read" :: list1)))  val list2 = list1.::("read").::("should").::("People") list2
Map State -> Capital is mapped to State -> length of the capital name valstateCapitals = Map( "Alabama" -> "Montgomery",   "Alaska"  -> "Juneau",   "Wyoming" -> "Cheyenne") vallengths = stateCapitalsmap { kv => (kv._1, kv._2.length)}  println(lengths) > Map(Alabama -> 10, Alaska -> 6, Wyoming -> 8)
FoldLeft deffoldLeft[B](z: B)(op: (B, A) => B): B =  thismatch{ caseNil => z case x :: xs => (xsfoldLeftop(z, x))(op) }
FoldLeft List(1,2,3,4,5).foldLeft(10)(_ * _) (((((10 * 1) * 2) * 3) * 4) * 5) List(1,2,3,4,5).foldLeft(10)( (x, y) => x +y) (((((10 + 1) + 2) + 3) + 4) + 5) Shortcut for arguments of anonymous functions. First underscore means the first argument, second the second…
Questions How would we write function “sum” with the help of foldLeft? defdistinct[A](l : List[A]) : List[A] =    (l foldLeft List[A]())      {(res, a)=> if (!res.contains(a)) a :: reselseres} defsumInt(l : List[Int]) : Int = l.foldLeft(0)(_ + _) How would we write function “distinct“with the help of foldLeft? (Selects only distinct elements form the list.)
Every value is an objectEvery operator a method factorial(x - 1) factorial (x.-(1)) map.containsKey(‘a’) map containsKey ‘a’ There are no operators in Scala. Method names can contain some symbols. Every method can be called on the object without the dot and the brackets.
There are no operators in Scala.  Method names can contain some symbols. trait Ordered[A] extendsjava.lang.Comparable[A] { def compare(that: A): Int def <  (that: A): Boolean = (this compare that) <  0 def >  (that: A): Boolean = (this compare that) >  0 def <= (that: A): Boolean = (this compare that) <= 0 def >= (that: A): Boolean = (this compare that) >= 0 defcompareTo(that: A): Int = compare(that) }
“While” doesn’t have to be a keyword...						   But it is... defwhileAwesome(conditional: => Boolean)(f: => Unit) { if (conditional) {     f whileAwesome(conditional)(f)   } } var count = 0 whileAwesome(count < 5) { println("still awesome")   count += 1 } >stillawesome stillawesome stillawesome stillawesome stillawesome Conditionalis of type (=> Boolean) , so it is evaluated in the function “whileAwesome” If conditionalwas of typeBoolean, it would be evaluated before calling the function so the loop would never stop writing"still awesome"
It has many real life uses tx{  valperson = new Person(id=null, name= "Ivanka");  manager.persist(person)  } deftx(f: => Unit) = { manager.getTransaction().begin() try { tx manager.getTransaction().commit()    } catch { casee: Exception => manager.getTransaction().rollback()    } }
Functions are objects too traitFunction1[-S, +T] { defapply(x: S):T } E.g. anonymous function (x: Int ) => x + 1 is translated by the compiler to new Function1[Int, Int] {    def apply(x: Int): Int = x + 1 }
Functions are objects too While (=>)is a class, it can be inherited from it. So we can specialize the concept of a function. Instead of a(i) = a(i) + 2 we can write a.update(i, a.apply(i) + 2) Array[T] is a function Int => T, so if such function is needed we can pass an Array[T] classArray[T] ( length: Int) extends(Int=> T) { deflength: Int= ... defapply(i: Int): T= ... defupdate(i: Int, x: T): Unit= ... defelements: Iterator[T] = ... defexists(p: T => Boolean):Boolean    = ... }
Currying Partial function application
Currying Function can return a function def cat(s1: String)(s2: String) = s1 + s2 def cat(s1: String) = (s2: String) => s1 + s2 cat("foo")("bar")  > java.lang.String = foobar cat("foo") returns a function {(s2 : Int) => “foo” + s2}, to which is passed an argument "bar"  Both notations are correct
Currying def cat(s1: String, s2: String) = s1 + s2 > cat: (String,String) java.lang.String valcurryCat = Function.curried(cat _) > curryCat: (String) => (String) => java.lang.String= <function> cat("foo", "bar") == curryCat("foo")("bar") > res2: Boolean = true Function.curried() converts functions to their curried form
Partial function application val curryCat = Function.curried(cat _) > curryCat: (String) => (String) => java.lang.String= <function> val partialCurryCat = curryCat("foo")(_) > partialCurryCat: (String) => java.lang.String = <function> partialCurryCat("bar") > res3: java.lang.String = foobar Partial application= we didn’t passed all parameters
Partial function application It is not needed to pass all parameters Uses Currying val numbers= List(1, 2, 3, 4, 5); println( numbers map ( 8 +)) def plus(a : Int)(b : Int) : Int = a + b val plusFive = plus(5) _ println( numbers map plusFive ) f(A : a)(B : b) : C f(B : b) : C
„There are two ways of constructing a software design.  One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies.” C.A.R. Hoare, author of Quicksort
Quicksort def sort(xs: Array[Int]) { defswap(i: Int, j: Int) { val t = xs(i); xs(i) = xs(j); xs(j) = t } def sort1(l: Int, r: Int) { val pivot = xs((l + r) / 2) var i = l; var j = r while (i <= j) { while (xs(i) < pivot) i += 1 while (xs(j) > pivot) j -= 1 if (i <= j) { swap(i, j) i += 1 j -= 1 } } if (l < j) sort1(l, j) if (j < r) sort1(i, r) } sort1(0, xs.length 1) } Functional Imperative def sort(xs: Array[Int]): Array[Int] = if (xs.length <= 1) xs else { val pivot = xs(xs.length / 2) Array.concat(         sort(xs filter (pivot >)), xs filter (pivot ==),         sort(xs filter (pivot <))) }
Implicits Implicit conversions
Implicits Only single implicit can be used (they can not chain)! println(intToPimpedInt(3).minutes()) implicitdefintToPimpedInt(i : Int) = newPimpedInt(i) defmain(args: Array[String]) { 	3 timesprintln("sdfs") println(5 minutes) } classPimpedInt(i : Int){ deftimes(f : => Unit) : Unit = for(x <- 0 until i) f defseconds = 1000 * i defminutes = 60 * seconds } intToPimpedInt(3).times(println("sdfs")) times(f : => Unit) seconds() minutes()
objectComplex { val i = newComplex(0, 1) implicitdef double2complex(x: Double) : Complex = newComplex(x, 0) } classComplex(valre: Double, val im: Double) { def + (that: Complex): Complex = new Complex(this.re + that.re, this.im + that.im) def - (that: Complex): Complex = new Complex(this.re - that.re, this.im - that.im) def * (that: Complex): Complex = new Complex(this.re * that.re - this.im * that.im, this.re * that.im + this.im * that.re) def / (that: Complex): Complex = {  valdenom = that.re * that.re + that.im * that.im new Complex((this.re * that.re + this.im * that.im) / denom,       		(this.im * that.re - this.re * that.im) / denom) } overridedeftoString = re+(if (im < 0) "-"+(-im) else"+"+im)+"*i" } By importing Complex one can use complex numbers like they were built in language feature. import pads.Complex._ objectComplexTest { defmain(args: Array[String]) { 		val x : Complex = 4 + 3 * i val y : Complex = x * i  println(y) } }
Structural typing “Type safe duck typing”
Structuraltyping classEmployee { varmeno : String = null } classFirm { var title : String = null def name = "Firm is called " + title } Attribute name Method name Employee and Firm does not have  a common supertype
Structural typing defgetName(x : {val name : String}) : String = x.name defsetName(x : {var name : String}) : Unit = x.name = "new name" val employee = new Employee() employee.name = “Kate" val firm = new Firm() firm.name = "PosAm" println (getName(employee)) println (getName(firm)) println (setName(employee)) println (setName(firm)) //ERROR type mismatch; found : firm.type (with underlying type pads.Firm) required: AnyRef{def name: String; defname_=(x$1: String): Unit}
DSL - domain specific language ImplicitsHigher order functionsOptional dots, semi-colons, parenthesesOperators like methodsCurrying
DSL External DSL 	+ own language, freedom 	- need to write a parser 	- extensible from inside Internal DSL 	+ extensible from outside,         it’s just a library 	- syntax of a host language Parser library in Scala simplifies writing external DSLs Implicits, higher-order functions,  optional dots and brackets, operator methods and currying simplifies writing of internal DSLs
External DSL written with the help of library scala.util.parsing.combinator._  /** @returnParser[Money] */ defpercentage = toBe ~> doubleNumber <~ "percent" <~ "of" <~ "gross"  ^^ { percentage => grossAmount * (percentage / 100.)   } defamount = toBe ~> doubleNumber <~ "in" <~ "gross" <~ "currency" ^^ {     Money(_)   } deftoBe = "is" | "are" defdoubleNumber = floatingPointNumber ^^ { _.toDouble } |, ~> , <~, ^^  are just functions Library pasing.combinator is internal DSL
^^  /** A parser combinator for function application       *      *<p>`p ^^ f' succeeds if `p' succeeds; it returns `f' applied to the result of `p'.</p>      *      * @param f a function that will be applied to this parser's result (see `map' in `ParseResult').      * @return a parser that has the same behaviour as the current parser, but whose result is      *         transformed by `f'.      */ def ^^ [U](f: T => U): Parser[U] = map(f).named(toString+"^^")
Trait Mixins Dependency injection  Data, context & interaction
Types Object has only a single instance. One can obtain this instance by writing object’s name. It can be extended by the Traits. Class can inherit from one class but it can be extended by several Traits. Like an interface/abstract class. Can have an implementation. Can not have a constructor. Class Object Trait
Dependency injection classUserRepository{ def authenticate(user: User): User = {    println("authenticating user: " + user)       user      }   def create(user: User) = println("creating user: " + user)   def delete(user: User) = println("deleting user: " + user)   }  classUserService {   def authenticate(username: String, password: String): User =    userRepository.authenticate(username, password)     def create(username: String, password: String) =    userRepository.create(new User(username, password))   def delete(user: User) = All is statically typed.     userRepository.delete(user)   }  UserService is dependent on UserRepository. It can have more implementations as well. UserRepository can have more implementations.
Cake Pattern traitUserRepositoryComponent{ valuserRepository: UserRepository classUserRepository {       ...     }   }  traitUserServiceComponent {  this: UserRepositoryComponent =>  valuserService: UserService classUserService {     ...    } } Classes are wrapped in components (traits), where its dependencies are declared.
Cake Pattern objectComponentRegistryextends  UserServiceComponentwith  UserRepositoryComponent { valuserRepository = newUserRepository valuserService = newUserService } In the result object we set implementations of all necessary components. Every component uses right implementation on which it is dependent.
Case class ADT Pattern matching
Pattern matching Matching by values Java swicht-case analogy valrandomInt = new Random().nextInt(10) randomIntmatch { case 7 => println( "lucky seven!" ) caseotherNumber => println(„not seven "+ otherNumber) }
Pattern matching Matching by type val sundries = List(23, "Hello", 8.5, 'q') for (sundry <- sundries) {     sundry match {  casei: Int          => println("got an Integer: " + i)  case s: String   => println("got a String: " + s)  case f: Double => println("got a Double: " + f)  case other        => println("got something else: " + other)     }  }

More Related Content

What's hot

Let the type system be your friend
Let the type system be your friendLet the type system be your friend
Let the type system be your friendThe Software House
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Datagreenwop
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side JavascriptJulie Iskander
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced JavascriptAdieu
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascriptMD Sayem Ahmed
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdajMario Fusco
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Chris Richardson
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APIMario Fusco
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioLuis Atencio
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingRichardWarburton
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional ProgrammingHugo Firth
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does notSergey Bandysik
 
Groovy Api Tutorial
Groovy Api  TutorialGroovy Api  Tutorial
Groovy Api Tutorialguligala
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondMario Fusco
 
Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8JavaDayUA
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Mario Fusco
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript FunctionsColin DeCarlo
 

What's hot (20)

Let the type system be your friend
Let the type system be your friendLet the type system be your friend
Let the type system be your friend
 
Category theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) DataCategory theory, Monads, and Duality in the world of (BIG) Data
Category theory, Monads, and Duality in the world of (BIG) Data
 
Introduction to Client-Side Javascript
Introduction to Client-Side JavascriptIntroduction to Client-Side Javascript
Introduction to Client-Side Javascript
 
Advanced Javascript
Advanced JavascriptAdvanced Javascript
Advanced Javascript
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
 
Sneaking inside Kotlin features
Sneaking inside Kotlin featuresSneaking inside Kotlin features
Sneaking inside Kotlin features
 
No more loops with lambdaj
No more loops with lambdajNo more loops with lambdaj
No more loops with lambdaj
 
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...Map(), flatmap() and reduce() are your new best friends: simpler collections,...
Map(), flatmap() and reduce() are your new best friends: simpler collections,...
 
Bw14
Bw14Bw14
Bw14
 
Let's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java APILet's make a contract: the art of designing a Java API
Let's make a contract: the art of designing a Java API
 
Functional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis AtencioFunctional Programming in JavaScript by Luis Atencio
Functional Programming in JavaScript by Luis Atencio
 
Twins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional ProgrammingTwins: Object Oriented Programming and Functional Programming
Twins: Object Oriented Programming and Functional Programming
 
Intro to Functional Programming
Intro to Functional ProgrammingIntro to Functional Programming
Intro to Functional Programming
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does not
 
Groovy Api Tutorial
Groovy Api  TutorialGroovy Api  Tutorial
Groovy Api Tutorial
 
FP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyondFP in Java - Project Lambda and beyond
FP in Java - Project Lambda and beyond
 
Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8Unlocking the Magic of Monads with Java 8
Unlocking the Magic of Monads with Java 8
 
Monadic Java
Monadic JavaMonadic Java
Monadic Java
 
Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...Laziness, trampolines, monoids and other functional amenities: this is not yo...
Laziness, trampolines, monoids and other functional amenities: this is not yo...
 
JavaScript Functions
JavaScript FunctionsJavaScript Functions
JavaScript Functions
 

Similar to Scala en

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
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scalaparag978978
 
Scala 3camp 2011
Scala   3camp 2011Scala   3camp 2011
Scala 3camp 2011Scalac
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In ScalaSkills Matter
 
Javascript Experiment
Javascript ExperimentJavascript Experiment
Javascript Experimentwgamboa
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescriptDavid Furber
 
Java 1.5 - whats new and modern patterns (2007)
Java 1.5 - whats new and modern patterns (2007)Java 1.5 - whats new and modern patterns (2007)
Java 1.5 - whats new and modern patterns (2007)Peter Antman
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009David Pollak
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVMVaclav Pech
 
On Scala Slides - OSDC 2009
On Scala Slides - OSDC 2009On Scala Slides - OSDC 2009
On Scala Slides - OSDC 2009Michael Neale
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrongJulien Wetterwald
 
My First Rails Plugin - Usertext
My First Rails Plugin - UsertextMy First Rails Plugin - Usertext
My First Rails Plugin - Usertextfrankieroberto
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScriptRasan Samarasinghe
 

Similar to Scala en (20)

Scala introduction
Scala introductionScala introduction
Scala introduction
 
Scala 2 + 2 > 4
Scala 2 + 2 > 4Scala 2 + 2 > 4
Scala 2 + 2 > 4
 
Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)Pragmatic Real-World Scala (short version)
Pragmatic Real-World Scala (short version)
 
Pragmatic Real-World Scala
Pragmatic Real-World ScalaPragmatic Real-World Scala
Pragmatic Real-World Scala
 
Scala 3camp 2011
Scala   3camp 2011Scala   3camp 2011
Scala 3camp 2011
 
Oscon 2010 Specs talk
Oscon 2010 Specs talkOscon 2010 Specs talk
Oscon 2010 Specs talk
 
Groovy
GroovyGroovy
Groovy
 
Rewriting Java In Scala
Rewriting Java In ScalaRewriting Java In Scala
Rewriting Java In Scala
 
Javascript Experiment
Javascript ExperimentJavascript Experiment
Javascript Experiment
 
Real life-coffeescript
Real life-coffeescriptReal life-coffeescript
Real life-coffeescript
 
Scala @ TomTom
Scala @ TomTomScala @ TomTom
Scala @ TomTom
 
Java 1.5 - whats new and modern patterns (2007)
Java 1.5 - whats new and modern patterns (2007)Java 1.5 - whats new and modern patterns (2007)
Java 1.5 - whats new and modern patterns (2007)
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
 
Concurrency on the JVM
Concurrency on the JVMConcurrency on the JVM
Concurrency on the JVM
 
Jquery 1
Jquery 1Jquery 1
Jquery 1
 
On Scala Slides - OSDC 2009
On Scala Slides - OSDC 2009On Scala Slides - OSDC 2009
On Scala Slides - OSDC 2009
 
A well-typed program never goes wrong
A well-typed program never goes wrongA well-typed program never goes wrong
A well-typed program never goes wrong
 
My First Rails Plugin - Usertext
My First Rails Plugin - UsertextMy First Rails Plugin - Usertext
My First Rails Plugin - Usertext
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
DIWE - Programming with JavaScript
DIWE - Programming with JavaScriptDIWE - Programming with JavaScript
DIWE - Programming with JavaScript
 

Recently uploaded

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure servicePooja Nehwal
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024Scott Keck-Warren
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsHyundai Motor Group
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slidespraypatel2
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 3652toLead Limited
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetEnjoy Anytime
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountPuma Security, LLC
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxMalak Abu Hammad
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersThousandEyes
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationSafe Software
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesSinan KOZAK
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsEnterprise Knowledge
 

Recently uploaded (20)

How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure serviceWhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
WhatsApp 9892124323 ✓Call Girls In Kalyan ( Mumbai ) secure service
 
SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024SQL Database Design For Developers at php[tek] 2024
SQL Database Design For Developers at php[tek] 2024
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter RoadsSnow Chain-Integrated Tire for a Safe Drive on Winter Roads
Snow Chain-Integrated Tire for a Safe Drive on Winter Roads
 
Slack Application Development 101 Slides
Slack Application Development 101 SlidesSlack Application Development 101 Slides
Slack Application Development 101 Slides
 
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
Tech-Forward - Achieving Business Readiness For Copilot in Microsoft 365
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your BudgetHyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
Hyderabad Call Girls Khairatabad ✨ 7001305949 ✨ Cheap Price Your Budget
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Breaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path MountBreaking the Kubernetes Kill Chain: Host Path Mount
Breaking the Kubernetes Kill Chain: Host Path Mount
 
Pigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping ElbowsPigging Solutions Piggable Sweeping Elbows
Pigging Solutions Piggable Sweeping Elbows
 
The Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptxThe Codex of Business Writing Software for Real-World Solutions 2.pptx
The Codex of Business Writing Software for Real-World Solutions 2.pptx
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for PartnersEnhancing Worker Digital Experience: A Hands-on Workshop for Partners
Enhancing Worker Digital Experience: A Hands-on Workshop for Partners
 
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry InnovationBeyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
Beyond Boundaries: Leveraging No-Code Solutions for Industry Innovation
 
Unblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen FramesUnblocking The Main Thread Solving ANRs and Frozen Frames
Unblocking The Main Thread Solving ANRs and Frozen Frames
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
IAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI SolutionsIAC 2024 - IA Fast Track to Search Focused AI Solutions
IAC 2024 - IA Fast Track to Search Focused AI Solutions
 

Scala en

  • 2. “I can honestly say if someone had shown me the Programming in Scala book by Martin Odersky, Lex Spoon & Bill Venners back in 2003 I'd probably have never created Groovy.“ JamesStrachan, Groovy creator
  • 3. “No other language on the JVM seems as capable of being a "replacement for Java" as Scala, and the momentum behind Scala is now unquestionable.“ CharlesNutter, JRubycoredeveloper
  • 4. “Scala.“ JamesGosling, Java creator Answer on a question, which language would he use now on JVM except Java.
  • 5. “On my radar, the current best exit strategy for Java is Scala.„ BruceEckel,author of many books
  • 6. Scala vs Java Scala removes break, continue, goto static primitive types raw types (every type parameter „generics“ has to be stated) operators (all are methods) override is not more optional (when overriding in Scala one has to declare override)
  • 7. Scala vs Ruby and Groovy Scala has two type of fans Java programmers (pros of functional programming) Ruby programmers (pros of language with static typing) Implicits, structural typing and type inference, resembles work with language with dynamic typing Scala is compiles a compiled language and all types are checked in compilation time one can not call a non existing method no ClassCastException in runtime possibility to refactor as fast as Java
  • 9. Why to unify FP and OOP Both approaches are complementary Functional Object-oriented Abstraction Functions Higher-order functions Parametric polymorphism Extending, state dependent behavior Inheritance Polymorphism Encapsulation Dynamic configuration
  • 10. Where? Manipulation of data structures collections, trees, ADTs, ... Internal/External DSLs OSGi, Apache Camel, scala-query, specs, built-in parser Modular applications Mixins, dependency injection, DCI (data, context & interaction)
  • 11.
  • 17. ImplicitsManipulation of data structures collections, trees, ADTs, ... Internal/External DSLs OSGi, Apache Camel, scala-query, specs, built-in parser Modular applications Mixins, dependency injection, DCI (data, context & interaction)
  • 18. Function as value Manipulation of data structures Collections Trees DSL
  • 19. Example - filtering Java public Collection<Ticket> approved(Collection<Ticket> tickets){ Collection<Ticket> result = new ArrayList<Ticket>(); for(Ticket ticket : tickets){ if(ticket.getState() == State.APPROVED) result.add(icket); } return result; }
  • 20. Example - filtering Java publicCollection<Ticket> approved(Collection<Ticket> tickets){ Collection<Ticket> result = new ArrayList<Ticket>(); for(Ticketticket: tickets){ filter if(ticket.getState()== State.APPROVED) result.add(ticket); } returnresult; } With what? What to do? How?
  • 21. Yes, it can be done in Java Interface for conditon ... and the use Filter util method publicinterfaceICondition<T> { publicbooleancheck(T toBeChecked); } publicstatic <T> Collection<T> filter(Collection<T> ts, ICondition<T> c){ Collection<T> result = new ArrayList<T>(); for(T t : ts) if(c.check(t)) result.add(t); returnresult; } CollestionUtils.filter(verzie, new ICondition<Ticket>() { public boolean check(TickettoBeChecked) { return toBeChecked.getState() == State.APPROVED; } });
  • 22. Example - filtering Scala defapproved(tickets: List[Ticket]) { tickets filter (_.getState() == State.APPROVED) }
  • 23. WTF ? What type has the parameter in the function „filter“? List[+A]{ deffilter (p : (A) => Boolean) : List[A] } Java : (A) => Boolean public interface Function1<O, I> { O apply(I input); } interface ICondition<I> extends IFunction1<Boolean, I> {}
  • 24. Scala List count (p : (A) => Boolean) :Int exists (p : (A) => Boolean) : Boolean filter (p : (A) => Boolean) : List[A] find (p : (A) => Boolean) : Option[A] foldLeft [B](z : B)(f : (B, A) => B) : B forall (p : (A) => Boolean) : Boolean foreach (f : (A) => Unit) : Unit map [B](f : (A) => B) : List[B] remove (p : (A) => Boolean) : List[A]
  • 25. Scala List Most of them is inherited from trait Iterable. So every collection, array has them, because they inherit from Iterable. Similar functions can be written for trees. count (p : (A) => Boolean) :Int exists (p : (A) => Boolean) : Boolean filter (p : (A) => Boolean) : List[A] find (p : (A) => Boolean) : Option[A] foldLeft [B](z : B)(f : (B, A) => B) : B forall (p : (A) => Boolean) : Boolean foreach (f : (A) => Unit) : Unit map [B](f : (A) => B) : List[B] remove (p : (A) => Boolean) : List[A]
  • 26. Function can be assigned to variable varf : (String => Unit) = (x) => println(x) Function can be passed to another function tickets filter (t => t.getState() == State.APPROVED) Return value from function can be a function defdeductKind = tax | insurance | retirement Function is primitive type, basic building block, with the same importance as an integer or a string. If functions takes another function as an argument or if it returns a function, it is called a higher-order function.
  • 27. Examples Numbers multiplied by two Employees to DTOs List(1, 2, 3, 4, 5) map { _ * 2 } > List[Int] = List(2, 4, 6, 8, 10) caseclassEmployee( varname : String) caseclass DTOEmployee( var name : String) deftoDto(e : Employee) = newDTOZamestnanec(z.meno) List(newEmployee(“John"), newEmployee(“Jack")) maptoDto > List[DTOEmployee] = List(DTOEmployee(John), DTOEmployee(Jack))
  • 28. Type declaration In Scala types are written after colon exists (p : (A) => Boolean) : Boolean var age :Int= 24 val age = 33 If type is unambiguous, it doesn’t have to be declared Return type of function exists Argument p is of type function from A to Boolean Type of variableage
  • 29.
  • 30. creates field, getter and setter varage:Int=22 age = 33
  • 31. List Operator :: is bound from right val list1 = List("Programming", "Scala") val list2 = "People" :: "should" :: "read" :: list1 val list2 = ("People" :: ("should" :: ("read" :: list1))) val list2 = list1.::("read").::("should").::("People") list2
  • 32. Map State -> Capital is mapped to State -> length of the capital name valstateCapitals = Map( "Alabama" -> "Montgomery", "Alaska" -> "Juneau", "Wyoming" -> "Cheyenne") vallengths = stateCapitalsmap { kv => (kv._1, kv._2.length)} println(lengths) > Map(Alabama -> 10, Alaska -> 6, Wyoming -> 8)
  • 33. FoldLeft deffoldLeft[B](z: B)(op: (B, A) => B): B = thismatch{ caseNil => z case x :: xs => (xsfoldLeftop(z, x))(op) }
  • 34. FoldLeft List(1,2,3,4,5).foldLeft(10)(_ * _) (((((10 * 1) * 2) * 3) * 4) * 5) List(1,2,3,4,5).foldLeft(10)( (x, y) => x +y) (((((10 + 1) + 2) + 3) + 4) + 5) Shortcut for arguments of anonymous functions. First underscore means the first argument, second the second…
  • 35. Questions How would we write function “sum” with the help of foldLeft? defdistinct[A](l : List[A]) : List[A] = (l foldLeft List[A]()) {(res, a)=> if (!res.contains(a)) a :: reselseres} defsumInt(l : List[Int]) : Int = l.foldLeft(0)(_ + _) How would we write function “distinct“with the help of foldLeft? (Selects only distinct elements form the list.)
  • 36. Every value is an objectEvery operator a method factorial(x - 1) factorial (x.-(1)) map.containsKey(‘a’) map containsKey ‘a’ There are no operators in Scala. Method names can contain some symbols. Every method can be called on the object without the dot and the brackets.
  • 37. There are no operators in Scala. Method names can contain some symbols. trait Ordered[A] extendsjava.lang.Comparable[A] { def compare(that: A): Int def < (that: A): Boolean = (this compare that) < 0 def > (that: A): Boolean = (this compare that) > 0 def <= (that: A): Boolean = (this compare that) <= 0 def >= (that: A): Boolean = (this compare that) >= 0 defcompareTo(that: A): Int = compare(that) }
  • 38. “While” doesn’t have to be a keyword... But it is... defwhileAwesome(conditional: => Boolean)(f: => Unit) { if (conditional) { f whileAwesome(conditional)(f) } } var count = 0 whileAwesome(count < 5) { println("still awesome") count += 1 } >stillawesome stillawesome stillawesome stillawesome stillawesome Conditionalis of type (=> Boolean) , so it is evaluated in the function “whileAwesome” If conditionalwas of typeBoolean, it would be evaluated before calling the function so the loop would never stop writing"still awesome"
  • 39. It has many real life uses tx{ valperson = new Person(id=null, name= "Ivanka"); manager.persist(person) } deftx(f: => Unit) = { manager.getTransaction().begin() try { tx manager.getTransaction().commit() } catch { casee: Exception => manager.getTransaction().rollback() } }
  • 40. Functions are objects too traitFunction1[-S, +T] { defapply(x: S):T } E.g. anonymous function (x: Int ) => x + 1 is translated by the compiler to new Function1[Int, Int] { def apply(x: Int): Int = x + 1 }
  • 41. Functions are objects too While (=>)is a class, it can be inherited from it. So we can specialize the concept of a function. Instead of a(i) = a(i) + 2 we can write a.update(i, a.apply(i) + 2) Array[T] is a function Int => T, so if such function is needed we can pass an Array[T] classArray[T] ( length: Int) extends(Int=> T) { deflength: Int= ... defapply(i: Int): T= ... defupdate(i: Int, x: T): Unit= ... defelements: Iterator[T] = ... defexists(p: T => Boolean):Boolean = ... }
  • 43. Currying Function can return a function def cat(s1: String)(s2: String) = s1 + s2 def cat(s1: String) = (s2: String) => s1 + s2 cat("foo")("bar") > java.lang.String = foobar cat("foo") returns a function {(s2 : Int) => “foo” + s2}, to which is passed an argument "bar" Both notations are correct
  • 44. Currying def cat(s1: String, s2: String) = s1 + s2 > cat: (String,String) java.lang.String valcurryCat = Function.curried(cat _) > curryCat: (String) => (String) => java.lang.String= <function> cat("foo", "bar") == curryCat("foo")("bar") > res2: Boolean = true Function.curried() converts functions to their curried form
  • 45. Partial function application val curryCat = Function.curried(cat _) > curryCat: (String) => (String) => java.lang.String= <function> val partialCurryCat = curryCat("foo")(_) > partialCurryCat: (String) => java.lang.String = <function> partialCurryCat("bar") > res3: java.lang.String = foobar Partial application= we didn’t passed all parameters
  • 46. Partial function application It is not needed to pass all parameters Uses Currying val numbers= List(1, 2, 3, 4, 5); println( numbers map ( 8 +)) def plus(a : Int)(b : Int) : Int = a + b val plusFive = plus(5) _ println( numbers map plusFive ) f(A : a)(B : b) : C f(B : b) : C
  • 47. „There are two ways of constructing a software design.  One way is to make it so simple that there are obviously no deficiencies. And the other way is to make it so complicated that there are no obvious deficiencies.” C.A.R. Hoare, author of Quicksort
  • 48. Quicksort def sort(xs: Array[Int]) { defswap(i: Int, j: Int) { val t = xs(i); xs(i) = xs(j); xs(j) = t } def sort1(l: Int, r: Int) { val pivot = xs((l + r) / 2) var i = l; var j = r while (i <= j) { while (xs(i) < pivot) i += 1 while (xs(j) > pivot) j -= 1 if (i <= j) { swap(i, j) i += 1 j -= 1 } } if (l < j) sort1(l, j) if (j < r) sort1(i, r) } sort1(0, xs.length 1) } Functional Imperative def sort(xs: Array[Int]): Array[Int] = if (xs.length <= 1) xs else { val pivot = xs(xs.length / 2) Array.concat( sort(xs filter (pivot >)), xs filter (pivot ==), sort(xs filter (pivot <))) }
  • 50. Implicits Only single implicit can be used (they can not chain)! println(intToPimpedInt(3).minutes()) implicitdefintToPimpedInt(i : Int) = newPimpedInt(i) defmain(args: Array[String]) { 3 timesprintln("sdfs") println(5 minutes) } classPimpedInt(i : Int){ deftimes(f : => Unit) : Unit = for(x <- 0 until i) f defseconds = 1000 * i defminutes = 60 * seconds } intToPimpedInt(3).times(println("sdfs")) times(f : => Unit) seconds() minutes()
  • 51. objectComplex { val i = newComplex(0, 1) implicitdef double2complex(x: Double) : Complex = newComplex(x, 0) } classComplex(valre: Double, val im: Double) { def + (that: Complex): Complex = new Complex(this.re + that.re, this.im + that.im) def - (that: Complex): Complex = new Complex(this.re - that.re, this.im - that.im) def * (that: Complex): Complex = new Complex(this.re * that.re - this.im * that.im, this.re * that.im + this.im * that.re) def / (that: Complex): Complex = { valdenom = that.re * that.re + that.im * that.im new Complex((this.re * that.re + this.im * that.im) / denom, (this.im * that.re - this.re * that.im) / denom) } overridedeftoString = re+(if (im < 0) "-"+(-im) else"+"+im)+"*i" } By importing Complex one can use complex numbers like they were built in language feature. import pads.Complex._ objectComplexTest { defmain(args: Array[String]) { val x : Complex = 4 + 3 * i val y : Complex = x * i println(y) } }
  • 52. Structural typing “Type safe duck typing”
  • 53. Structuraltyping classEmployee { varmeno : String = null } classFirm { var title : String = null def name = "Firm is called " + title } Attribute name Method name Employee and Firm does not have a common supertype
  • 54. Structural typing defgetName(x : {val name : String}) : String = x.name defsetName(x : {var name : String}) : Unit = x.name = "new name" val employee = new Employee() employee.name = “Kate" val firm = new Firm() firm.name = "PosAm" println (getName(employee)) println (getName(firm)) println (setName(employee)) println (setName(firm)) //ERROR type mismatch; found : firm.type (with underlying type pads.Firm) required: AnyRef{def name: String; defname_=(x$1: String): Unit}
  • 55. DSL - domain specific language ImplicitsHigher order functionsOptional dots, semi-colons, parenthesesOperators like methodsCurrying
  • 56. DSL External DSL + own language, freedom - need to write a parser - extensible from inside Internal DSL + extensible from outside, it’s just a library - syntax of a host language Parser library in Scala simplifies writing external DSLs Implicits, higher-order functions, optional dots and brackets, operator methods and currying simplifies writing of internal DSLs
  • 57. External DSL written with the help of library scala.util.parsing.combinator._ /** @returnParser[Money] */ defpercentage = toBe ~> doubleNumber <~ "percent" <~ "of" <~ "gross" ^^ { percentage => grossAmount * (percentage / 100.) } defamount = toBe ~> doubleNumber <~ "in" <~ "gross" <~ "currency" ^^ { Money(_) } deftoBe = "is" | "are" defdoubleNumber = floatingPointNumber ^^ { _.toDouble } |, ~> , <~, ^^ are just functions Library pasing.combinator is internal DSL
  • 58. ^^ /** A parser combinator for function application * *<p>`p ^^ f' succeeds if `p' succeeds; it returns `f' applied to the result of `p'.</p> * * @param f a function that will be applied to this parser's result (see `map' in `ParseResult'). * @return a parser that has the same behaviour as the current parser, but whose result is * transformed by `f'. */ def ^^ [U](f: T => U): Parser[U] = map(f).named(toString+"^^")
  • 59. Trait Mixins Dependency injection Data, context & interaction
  • 60. Types Object has only a single instance. One can obtain this instance by writing object’s name. It can be extended by the Traits. Class can inherit from one class but it can be extended by several Traits. Like an interface/abstract class. Can have an implementation. Can not have a constructor. Class Object Trait
  • 61. Dependency injection classUserRepository{ def authenticate(user: User): User = { println("authenticating user: " + user) user } def create(user: User) = println("creating user: " + user) def delete(user: User) = println("deleting user: " + user) } classUserService { def authenticate(username: String, password: String): User = userRepository.authenticate(username, password) def create(username: String, password: String) = userRepository.create(new User(username, password)) def delete(user: User) = All is statically typed. userRepository.delete(user) } UserService is dependent on UserRepository. It can have more implementations as well. UserRepository can have more implementations.
  • 62. Cake Pattern traitUserRepositoryComponent{ valuserRepository: UserRepository classUserRepository { ... } } traitUserServiceComponent { this: UserRepositoryComponent => valuserService: UserService classUserService { ... } } Classes are wrapped in components (traits), where its dependencies are declared.
  • 63. Cake Pattern objectComponentRegistryextends UserServiceComponentwith UserRepositoryComponent { valuserRepository = newUserRepository valuserService = newUserService } In the result object we set implementations of all necessary components. Every component uses right implementation on which it is dependent.
  • 64. Case class ADT Pattern matching
  • 65. Pattern matching Matching by values Java swicht-case analogy valrandomInt = new Random().nextInt(10) randomIntmatch { case 7 => println( "lucky seven!" ) caseotherNumber => println(„not seven "+ otherNumber) }
  • 66. Pattern matching Matching by type val sundries = List(23, "Hello", 8.5, 'q') for (sundry <- sundries) { sundry match { casei: Int => println("got an Integer: " + i) case s: String => println("got a String: " + s) case f: Double => println("got a Double: " + f) case other => println("got something else: " + other) } }
  • 67. Pattern matching Matching of sequences valwillWork = List(1, 3, 23, 90) valwillNotWork = List(4, 18, 52) val empty = List() for (l <- List(willWork, willNotWork, empty)) { l match { case List(_, 3, _, _) => println("4 elements, with the 2nd being '3'.") case List(_*) => println("Any other list with 0 or more elements.") } }
  • 68. Pattern matching Matching of tuples valtupA = ("Good", "Morning!") valtupB = ("Guten", "Tag!") for(tup <- List(tupA, tupB)) { tupmatch { case(thingOne, thingTwo) ifthingOne == "Good" => println("A two-tuple starting with 'Good'.") case(thingOne, thingTwo) => println("Two things: " + thingOne + " and " + thingTwo) } }
  • 69. Pattern matching Matching of case classes caseclass Person(name: String, age: Int) valalice = new Person("Alice", 25) val bob = new Person("Bob", 32) valcharlie = new Person("Charlie", 32) for (person <- List(alice, bob, charlie)) { person match { case Person("Alice",25) => println("Hi Alice!") case Person("Bob", 32) => println("Hi Bob!") case Person(name, age) => println(age + " years old person named " + name ) } }
  • 70. Recap Scala is a multi-paradigm language Object-oriented – objects, classes, traits, inheritance, polymorphism, encapsulation Functional – function is a value, pattern matching, parametric polymorphism (generics), case classes (Dynamic-types) – implicits, traits, structural typing, type inference These features give programmers a feel of language with dynamic types. Although all types are checked in compilation time.
  • 71. And I haven’t mention Implicit function parameters Lazy values XML built in syntax Actor ... And it works with Hibernate, Spring, Guice, Maven, Wicket...
  • 72. Want to know more? programming-scala.labs.oreilly.com www.scala-lang.org