SlideShare a Scribd company logo
1 of 56
A Brief Intro to Scala Tim Underwood
About Me Tim Underwood Co-Founder of Frugal Mechanic Software Developer Perl, PHP, C, C++, C#, Java, Ruby and now Scala Before Scaladefault languages were Ruby and Java
Dynamic vs. Static Dynamic (Ruby) Static (Java) Concise Scriptable Read-Eval-Print Loop (irb) Higher Order Functions Extend existing classes Duck Typing method_missing Better IDE Support Fewer Tests Documentation Open Source Libs Performance JVM Tools (VisualVM) True Multi-threading
Scala ,[object Object]
Scriptable
Read-Eval-Print Loop
Higher Order Functions
Extend existing classes
Duck Typing
method_missing
Better IDE Support
Fewer Tests
Documentation
Open Source Libs
Performance
JVM Tools (VisualVM)
True Multi-threading,[object Object]
Scalais a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way.
Scala Statically Typed Runs on JVM, full inter-op with Java Object Oriented Functional Dynamic Features
Scala is Practical Can be used as drop-in replacement for Java Mixed Scala/Java projects Use existing Java libraries Use existing Java tools (Ant, Maven, JUnit, etc…) Decent IDE Support (NetBeans, IntelliJ, Eclipse)
Scala is Concise
Type Inference val sum = 1 + 2 + 3 valnums = List(1, 2, 3) val map = Map("abc" -> List(1,2,3))
Explicit Types val sum:Int= 1 + 2 + 3 valnums:List[Int]= List(1, 2, 3) val map:Map[String, List[Int]] = ...
Higher Level // Java – Check if string has uppercase character booleanhasUpperCase = false; for(inti = 0; i < name.length(); i++) { if(Character.isUpperCase(name.charAt(i))) { hasUpperCase = true; break;     } }
Higher Level // Scala valhasUpperCase = name.exists(_.isUpperCase)
Less Boilerplate // Java public class Person { private String name; private intage; public Person(String name, Intage) {  // constructor     this.name = name; this.age = age;   } public String getName() {              // name getter     return name;   } publicintgetAge() {                  // age getter     return age;   } public void setName(Stringname) {     // name setter     this.name = name;   } public void setAge(intage) {          // age setter this.age = age;   } }
Less Boilerplate // Scala class Person(varname: String, varage: Int)
Less Boilerplate // Scala class Person(var name: String, privatevar _age: Int) {   defage = _age// Getter for age   defage_=(newAge:Int) {  // Setter for age println("Changing age to: "+newAge) _age = newAge   } }
Variables and Values // variable varfoo = "foo" foo = "bar"  // okay // value valbar = "bar" bar = "foo"// nope
Scala is Object Oriented
Pure O.O. // Every value is an object 1.toString // Every operation is a method call 1 + 2 + 3    (1).+(2).+(3) // Can omit . and ( ) "abc" charAt 1    "abc".charAt(1)
Classes // Classes (and abstract classes) like Java abstract classLanguage(valname:String) { override deftoString = name } // Example implementations classScalaextendsLanguage("Scala") // Anonymous class valscala = newLanguage("Scala") { /* empty */ }
Traits // Like interfaces in Java trait Language { valname:String // But allow implementation overridedeftoString = name }
Traits traitJVM {    override deftoString = super.toString+" runs on JVM" } traitStatic {   override deftoString = super.toString+" is Static" } // Traits are stackable classScalaextends Language with JVM with Static { val name = "Scala" } println(newScala) "Scala runs on JVM is Static"
Singleton Objects // Replaces static methods from Java // Can extend/implement classes & traits object Hello {   def world = println("Hello World"} } Hello.world  Hello World
Scala is Functional
First Class Functions // Lightweight anonymous functions (x:Int) => x + 1 // Calling the anonymous function valplusOne = (x:Int) => x + 1 plusOne(5)    6
Closures // plusFoo can reference any values/variables in scope varfoo= 1 valplusFoo = (x:Int) => x + foo plusFoo(5)      6 // Changing foo changes the return value of plusFoo foo= 5 plusFoo(5)      10
Higher Order Functions valplusOne = (x:Int) => x + 1 valnums = List(1,2,3) // map takes a function: Int => T nums.map(plusOne)       List(2,3,4) // Inline Anonymous nums.map(x => x + 1)    List(2,3,4) // Short form nums.map(_ + 1)         List(2,3,4)
Higher Order Functions valnums = List(1,2,3,4) // A few more examples for List class nums.exists(_ == 2)          true nums.find(_ == 2)            Some(2) nums.indexWhere(_ == 2)      1 nums.reduceLeft(_ + _)       10 nums.foldLeft(100)(_ + _)    110 // Many more in collections library
Higher Order Functions // functions as parameters defcall(f: Int => Int) = f(1) call(plusOne)       2 call(x => x + 1)    2 call(_ + 1)         2
Higher Order Functions // functions as parameters defeach(xs: List[Int], fun: Int => Unit) { if(!xs.isEmpty) { fun(xs.head) each(xs.tail, fun)   } } each(List(1,2,3), println)   1   2   3
Higher Order Functions // More complex example with generics & patternmatching @tailrec defeach[T](xs: List[T], fun: T => Unit): Unit = xsmatch{ caseNil => casehead :: tail => fun(head); each(tail, fun) } each(List(1,2), println)   1   2 each(List("foo", "bar"), println) foo   bar
Pattern Matching def what(any:Any) = any match { casei:Int => "It's an Int" cases:String => "It's a String" case_ => "I don't know what it is" } what(123)       "It's an Int" what("hello")   "It's a String" what(false)     "I don't know what it is"
Pattern Matching valnums = List(1,2,3) // Pattern matching to create 3 vals valList(a,b,c) = nums a      1 b  2 c  3
Immutable Types // Immutable types by default varnums = Set(1,2,3) nums+= 4  nums= nums.+(4) // Mutable types available importscala.collection.mutable._ valnums = Set(1,2,3) nums+= 4  nums.+=(4)
scala.collection
scala.collection.immutable
scala.collection.mutable
Or Use Existing Java Collections java.util Apache Commons Collections fastutil Trove Google Collections scala.collection.JavaConversion available to convert to and from java.util Interfaces
Scalais Dynamic (Okay not really, but it has lots of features typically only found in Dynamic languages)
Scriptable // HelloWorld.scala println("Hello World") bash$scalaHelloWorld.scala Hello World bash$scala -e 'println("Hello World")' Hello World
Read-Eval-Print Loop bash$scala Welcome to Scala version 2.8.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_22). Type in expressions to have them evaluated. Type :help for more information. scala>class Foo { def bar = "baz" } defined class Foo scala>valf = new Foo f: Foo = Foo@51707653 scala> f.bar res2: java.lang.String = baz
Structural Typing // Type safe Duck Typing def doTalk(any:{deftalk:String}) { println(any.talk) } class Duck { def talk = "Quack" } class Dog  { def talk = "Bark"  } doTalk(new Duck)    "Quack" doTalk(new Dog)     "Bark"
Implicit Conversions // Extend existing classes in a type safe way // Goal: Add isBlank method to String class classRichString(s:String) {    defisBlank = null == s || "" == s.trim } implicit deftoRichString(s:String) = newRichString(s) // Our isBlank method is now available on Strings " ".isBlanktrue "foo".isBlankfalse
Implicit Conversions // Does not type check "abc".isBlank // Search in-scope implicitsdefs that take a // String & return a type with an isBlank method implicit deftoRichString(s:String):RichString // Resulting code that type checks newRichString("abc").isBlank

More Related Content

What's hot

Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...Philip Schwarz
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the WildJosé Paumard
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaWiem Zine Elabidine
 
Writing Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UIWriting Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UIYnon Perek
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Philip Schwarz
 
Strings in Java
Strings in Java Strings in Java
Strings in Java Hitesh-Java
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsNewCircle Training
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language Hitesh-Java
 
Functional Domain Modeling - The ZIO 2 Way
Functional Domain Modeling - The ZIO 2 WayFunctional Domain Modeling - The ZIO 2 Way
Functional Domain Modeling - The ZIO 2 WayDebasish Ghosh
 
Hash table in java
Hash table in javaHash table in java
Hash table in javasiriindian
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionRichard Paul
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)arvind pandey
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Edureka!
 

What's hot (20)

Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...Algebraic Data Types forData Oriented Programming - From Haskell and Scala t...
Algebraic Data Types for Data Oriented Programming - From Haskell and Scala t...
 
Preparing for Scala 3
Preparing for Scala 3Preparing for Scala 3
Preparing for Scala 3
 
Collectors in the Wild
Collectors in the WildCollectors in the Wild
Collectors in the Wild
 
ZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in ScalaZIO: Powerful and Principled Functional Programming in Scala
ZIO: Powerful and Principled Functional Programming in Scala
 
Cheat Sheet java
Cheat Sheet javaCheat Sheet java
Cheat Sheet java
 
Laravel Introduction
Laravel IntroductionLaravel Introduction
Laravel Introduction
 
Unix shell scripts
Unix shell scriptsUnix shell scripts
Unix shell scripts
 
Writing Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UIWriting Reusable Web Components with jQuery and jQuery UI
Writing Reusable Web Components with jQuery and jQuery UI
 
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
Folding Unfolded - Polyglot FP for Fun and Profit - Haskell and Scala - with ...
 
Optional in Java 8
Optional in Java 8Optional in Java 8
Optional in Java 8
 
Strings in Java
Strings in Java Strings in Java
Strings in Java
 
Java 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & StreamsJava 8 Lambda Expressions & Streams
Java 8 Lambda Expressions & Streams
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Elements of Java Language
Elements of Java Language Elements of Java Language
Elements of Java Language
 
Functional Domain Modeling - The ZIO 2 Way
Functional Domain Modeling - The ZIO 2 WayFunctional Domain Modeling - The ZIO 2 Way
Functional Domain Modeling - The ZIO 2 Way
 
Hash table in java
Hash table in javaHash table in java
Hash table in java
 
Java
JavaJava
Java
 
Introduction to Spring's Dependency Injection
Introduction to Spring's Dependency InjectionIntroduction to Spring's Dependency Injection
Introduction to Spring's Dependency Injection
 
Core java complete ppt(note)
Core java  complete  ppt(note)Core java  complete  ppt(note)
Core java complete ppt(note)
 
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...Python Functions Tutorial | Working With Functions In Python | Python Trainin...
Python Functions Tutorial | Working With Functions In Python | Python Trainin...
 

Viewers also liked

Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scalapramode_ce
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Martin Odersky
 
Apache Spark MLlib - Random Foreset and Desicion Trees
Apache Spark MLlib - Random Foreset and Desicion TreesApache Spark MLlib - Random Foreset and Desicion Trees
Apache Spark MLlib - Random Foreset and Desicion TreesTuhin Mahmud
 
Spark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. JyotiskaSpark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. JyotiskaSigmoid
 
Build a deep learning pipeline on apache spark for ads optimization
Build a deep learning pipeline on apache spark for ads optimizationBuild a deep learning pipeline on apache spark for ads optimization
Build a deep learning pipeline on apache spark for ads optimizationCraig Chao
 

Viewers also liked (10)

Introduction to Functional Programming with Scala
Introduction to Functional Programming with ScalaIntroduction to Functional Programming with Scala
Introduction to Functional Programming with Scala
 
Scala, just a better java?
Scala, just a better java?Scala, just a better java?
Scala, just a better java?
 
Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009Scala Talk at FOSDEM 2009
Scala Talk at FOSDEM 2009
 
Apache Spark MLlib - Random Foreset and Desicion Trees
Apache Spark MLlib - Random Foreset and Desicion TreesApache Spark MLlib - Random Foreset and Desicion Trees
Apache Spark MLlib - Random Foreset and Desicion Trees
 
Apache spark Intro
Apache spark IntroApache spark Intro
Apache spark Intro
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala and spark
Scala and sparkScala and spark
Scala and spark
 
Spark workshop
Spark workshopSpark workshop
Spark workshop
 
Spark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. JyotiskaSpark Dataframe - Mr. Jyotiska
Spark Dataframe - Mr. Jyotiska
 
Build a deep learning pipeline on apache spark for ads optimization
Build a deep learning pipeline on apache spark for ads optimizationBuild a deep learning pipeline on apache spark for ads optimization
Build a deep learning pipeline on apache spark for ads optimization
 

Similar to A Brief Intro to Scala

Intro to scala
Intro to scalaIntro to scala
Intro to scalaJoe Zulli
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersMatthew Farwell
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009David Pollak
 
(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
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from javaIndicThreads
 
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 jvmIsaias Barroso
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecLoïc Descotte
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala MakeoverGarth Gilmour
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Troy Miles
 

Similar to A Brief Intro to Scala (20)

Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Scala in Places API
Scala in Places APIScala in Places API
Scala in Places API
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developersSoftshake 2013: 10 reasons why java developers are jealous of Scala developers
Softshake 2013: 10 reasons why java developers are jealous of Scala developers
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Beginning Scala Svcc 2009
Beginning Scala Svcc 2009Beginning Scala Svcc 2009
Beginning Scala Svcc 2009
 
Scala
ScalaScala
Scala
 
(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?
 
ES6 and BEYOND
ES6 and BEYONDES6 and BEYOND
ES6 and BEYOND
 
Scala collections api expressivity and brevity upgrade from java
Scala collections api  expressivity and brevity upgrade from javaScala collections api  expressivity and brevity upgrade from java
Scala collections api expressivity and brevity upgrade from java
 
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
 
Workshop Scala
Workshop ScalaWorkshop Scala
Workshop Scala
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar ProkopecScala presentation by Aleksandar Prokopec
Scala presentation by Aleksandar Prokopec
 
The Great Scala Makeover
The Great Scala MakeoverThe Great Scala Makeover
The Great Scala Makeover
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1Game Design and Development Workshop Day 1
Game Design and Development Workshop Day 1
 

Recently uploaded

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processorsdebabhi2
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsRoshan Dwivedi
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyKhushali Kathiriya
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAndrey Devyatkin
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingEdi Saputra
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024The Digital Insurer
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘RTylerCroy
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)wesley chun
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...DianaGray10
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...apidays
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodJuan lago vázquez
 

Recently uploaded (20)

Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live StreamsTop 5 Benefits OF Using Muvi Live Paywall For Live Streams
Top 5 Benefits OF Using Muvi Live Paywall For Live Streams
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law DevelopmentsTrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
TrustArc Webinar - Stay Ahead of US State Data Privacy Law Developments
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
AWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of TerraformAWS Community Day CPH - Three problems of Terraform
AWS Community Day CPH - Three problems of Terraform
 
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
Bajaj Allianz Life Insurance Company - Insurer Innovation Award 2024
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
+971581248768>> SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHA...
 
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost SavingRepurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
Repurposing LNG terminals for Hydrogen Ammonia: Feasibility and Cost Saving
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024Tata AIG General Insurance Company - Insurer Innovation Award 2024
Tata AIG General Insurance Company - Insurer Innovation Award 2024
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
🐬 The future of MySQL is Postgres 🐘
🐬  The future of MySQL is Postgres   🐘🐬  The future of MySQL is Postgres   🐘
🐬 The future of MySQL is Postgres 🐘
 
Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)Powerful Google developer tools for immediate impact! (2023-24 C)
Powerful Google developer tools for immediate impact! (2023-24 C)
 
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
Connector Corner: Accelerate revenue generation using UiPath API-centric busi...
 
Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...Apidays New York 2024 - The value of a flexible API Management solution for O...
Apidays New York 2024 - The value of a flexible API Management solution for O...
 
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin WoodPolkadot JAM Slides - Token2049 - By Dr. Gavin Wood
Polkadot JAM Slides - Token2049 - By Dr. Gavin Wood
 

A Brief Intro to Scala

  • 1. A Brief Intro to Scala Tim Underwood
  • 2. About Me Tim Underwood Co-Founder of Frugal Mechanic Software Developer Perl, PHP, C, C++, C#, Java, Ruby and now Scala Before Scaladefault languages were Ruby and Java
  • 3. Dynamic vs. Static Dynamic (Ruby) Static (Java) Concise Scriptable Read-Eval-Print Loop (irb) Higher Order Functions Extend existing classes Duck Typing method_missing Better IDE Support Fewer Tests Documentation Open Source Libs Performance JVM Tools (VisualVM) True Multi-threading
  • 4.
  • 17.
  • 18. Scalais a modern multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way.
  • 19. Scala Statically Typed Runs on JVM, full inter-op with Java Object Oriented Functional Dynamic Features
  • 20. Scala is Practical Can be used as drop-in replacement for Java Mixed Scala/Java projects Use existing Java libraries Use existing Java tools (Ant, Maven, JUnit, etc…) Decent IDE Support (NetBeans, IntelliJ, Eclipse)
  • 22. Type Inference val sum = 1 + 2 + 3 valnums = List(1, 2, 3) val map = Map("abc" -> List(1,2,3))
  • 23. Explicit Types val sum:Int= 1 + 2 + 3 valnums:List[Int]= List(1, 2, 3) val map:Map[String, List[Int]] = ...
  • 24. Higher Level // Java – Check if string has uppercase character booleanhasUpperCase = false; for(inti = 0; i < name.length(); i++) { if(Character.isUpperCase(name.charAt(i))) { hasUpperCase = true; break; } }
  • 25. Higher Level // Scala valhasUpperCase = name.exists(_.isUpperCase)
  • 26. Less Boilerplate // Java public class Person { private String name; private intage; public Person(String name, Intage) { // constructor this.name = name; this.age = age; } public String getName() { // name getter return name; } publicintgetAge() { // age getter return age; } public void setName(Stringname) { // name setter this.name = name; } public void setAge(intage) { // age setter this.age = age; } }
  • 27. Less Boilerplate // Scala class Person(varname: String, varage: Int)
  • 28. Less Boilerplate // Scala class Person(var name: String, privatevar _age: Int) { defage = _age// Getter for age defage_=(newAge:Int) { // Setter for age println("Changing age to: "+newAge) _age = newAge } }
  • 29. Variables and Values // variable varfoo = "foo" foo = "bar" // okay // value valbar = "bar" bar = "foo"// nope
  • 30. Scala is Object Oriented
  • 31. Pure O.O. // Every value is an object 1.toString // Every operation is a method call 1 + 2 + 3  (1).+(2).+(3) // Can omit . and ( ) "abc" charAt 1  "abc".charAt(1)
  • 32. Classes // Classes (and abstract classes) like Java abstract classLanguage(valname:String) { override deftoString = name } // Example implementations classScalaextendsLanguage("Scala") // Anonymous class valscala = newLanguage("Scala") { /* empty */ }
  • 33. Traits // Like interfaces in Java trait Language { valname:String // But allow implementation overridedeftoString = name }
  • 34. Traits traitJVM { override deftoString = super.toString+" runs on JVM" } traitStatic { override deftoString = super.toString+" is Static" } // Traits are stackable classScalaextends Language with JVM with Static { val name = "Scala" } println(newScala) "Scala runs on JVM is Static"
  • 35. Singleton Objects // Replaces static methods from Java // Can extend/implement classes & traits object Hello { def world = println("Hello World"} } Hello.world Hello World
  • 37. First Class Functions // Lightweight anonymous functions (x:Int) => x + 1 // Calling the anonymous function valplusOne = (x:Int) => x + 1 plusOne(5)  6
  • 38. Closures // plusFoo can reference any values/variables in scope varfoo= 1 valplusFoo = (x:Int) => x + foo plusFoo(5)  6 // Changing foo changes the return value of plusFoo foo= 5 plusFoo(5)  10
  • 39. Higher Order Functions valplusOne = (x:Int) => x + 1 valnums = List(1,2,3) // map takes a function: Int => T nums.map(plusOne)  List(2,3,4) // Inline Anonymous nums.map(x => x + 1)  List(2,3,4) // Short form nums.map(_ + 1)  List(2,3,4)
  • 40. Higher Order Functions valnums = List(1,2,3,4) // A few more examples for List class nums.exists(_ == 2)  true nums.find(_ == 2)  Some(2) nums.indexWhere(_ == 2)  1 nums.reduceLeft(_ + _)  10 nums.foldLeft(100)(_ + _)  110 // Many more in collections library
  • 41. Higher Order Functions // functions as parameters defcall(f: Int => Int) = f(1) call(plusOne)  2 call(x => x + 1)  2 call(_ + 1)  2
  • 42. Higher Order Functions // functions as parameters defeach(xs: List[Int], fun: Int => Unit) { if(!xs.isEmpty) { fun(xs.head) each(xs.tail, fun) } } each(List(1,2,3), println)  1  2  3
  • 43. Higher Order Functions // More complex example with generics & patternmatching @tailrec defeach[T](xs: List[T], fun: T => Unit): Unit = xsmatch{ caseNil => casehead :: tail => fun(head); each(tail, fun) } each(List(1,2), println)  1  2 each(List("foo", "bar"), println) foo  bar
  • 44. Pattern Matching def what(any:Any) = any match { casei:Int => "It's an Int" cases:String => "It's a String" case_ => "I don't know what it is" } what(123)  "It's an Int" what("hello")  "It's a String" what(false)  "I don't know what it is"
  • 45. Pattern Matching valnums = List(1,2,3) // Pattern matching to create 3 vals valList(a,b,c) = nums a  1 b 2 c 3
  • 46. Immutable Types // Immutable types by default varnums = Set(1,2,3) nums+= 4 nums= nums.+(4) // Mutable types available importscala.collection.mutable._ valnums = Set(1,2,3) nums+= 4 nums.+=(4)
  • 50. Or Use Existing Java Collections java.util Apache Commons Collections fastutil Trove Google Collections scala.collection.JavaConversion available to convert to and from java.util Interfaces
  • 51. Scalais Dynamic (Okay not really, but it has lots of features typically only found in Dynamic languages)
  • 52. Scriptable // HelloWorld.scala println("Hello World") bash$scalaHelloWorld.scala Hello World bash$scala -e 'println("Hello World")' Hello World
  • 53. Read-Eval-Print Loop bash$scala Welcome to Scala version 2.8.1.final (Java HotSpot(TM) 64-Bit Server VM, Java 1.6.0_22). Type in expressions to have them evaluated. Type :help for more information. scala>class Foo { def bar = "baz" } defined class Foo scala>valf = new Foo f: Foo = Foo@51707653 scala> f.bar res2: java.lang.String = baz
  • 54. Structural Typing // Type safe Duck Typing def doTalk(any:{deftalk:String}) { println(any.talk) } class Duck { def talk = "Quack" } class Dog { def talk = "Bark" } doTalk(new Duck)  "Quack" doTalk(new Dog)  "Bark"
  • 55. Implicit Conversions // Extend existing classes in a type safe way // Goal: Add isBlank method to String class classRichString(s:String) { defisBlank = null == s || "" == s.trim } implicit deftoRichString(s:String) = newRichString(s) // Our isBlank method is now available on Strings " ".isBlanktrue "foo".isBlankfalse
  • 56. Implicit Conversions // Does not type check "abc".isBlank // Search in-scope implicitsdefs that take a // String & return a type with an isBlank method implicit deftoRichString(s:String):RichString // Resulting code that type checks newRichString("abc").isBlank
  • 57. method_missing(Scala 2.9 Feature) // Dynamic is a marker trait used by the compiler classFooextendsDynamic { deftyped[T] = error("not implemented") defapplyDynamic(name:String)(args:Any*) = { println("called: "+name+"("+args.mkString(",")+")") } } valf = newFoo f.helloWorld called: helloWorld() f.hello("world") called: hello(world) f.bar(1,2,3) called: bar(1,2,3)
  • 58. Scala has tons of other cool stuff
  • 59. Default Parameter Values defhello(foo:Int= 0, bar:Int= 0) { println("foo: "+foo+" bar: "+bar) } hello()foo: 0 bar: 0 hello(1)foo: 1 bar: 0 hello(1,2)foo: 1 bar: 2
  • 60. Named Parameters defhello(foo:Int = 0, bar:Int = 0) { println("foo: "+foo+" bar: "+bar) } hello(bar=6) foo: 0 bar: 6 hello(foo=7) foo: 7 bar: 0 hello(foo=8,bar=9) foo: 8 bar: 9
  • 61. Everything Returns a Value val a = if(true) "yes" else "no" valb =try{ "foo" } catch { case _ => "error" } valc = { println("hello") "foo" }
  • 62. Lazy Vals // initialized on first access lazyvalfoo = { println("init") "bar" } foo init foo foo
  • 63. Nested Functions // Can nest multiple levels of functions def outer() { varmsg = "foo" def one() { def two() { def three() { println(msg) } three() } two() } one() }
  • 64. By-Name Parameters // msg parameter automatically wrapped in closure deflog(doLog:Boolean, msg: => String) { if(doLog) { msg// evaluates msg msg// evaluates msg again! } } deffoo:String = { println("infoo"); "Foo" } log(true, foo+" Bar") // foo called twice  in foo  in foo log(false, foo+" Bar") // foo never called
  • 65. Many More Features Actors Annotations @foo def hello = "world" Case Classes case class Foo(bar:String) Curryingdef foo(a:Int,b:Boolean)(c:String) For Comprehensions for(i <- 1.to(5) if i % 2 == 0) yield i Genericsclass Foo[T](bar:T) Package Objects Partially Applied Functions Tuplesvalt = (1,"foo","bar") Type Specialization XML Literals val node = <hello>world</hello> etc…
  • 66. Personal Experiences Productive from Day 1 Drop in replacement for Java giving you more Ruby-like syntax and features Can pickup the functional and higher-level programming concepts as you go
  • 67. Great Book for a Deep Dive into Scala