This document provides an introduction to the Scala programming language. It begins with an overview of Scala's motivation and history. It then covers the basics of Scala including simple data structures, loops, objects, types and generics. More advanced topics such as traits, mixins, implicit conversions and sealed classes are also discussed. The document concludes with references for further reading.
Scala is an object-oriented and functional programming language that runs on the Java Virtual Machine. It was designed by Martin Odersky and developed at EPFL in Switzerland. Scala combines object-oriented and functional programming principles, including support for immutable data structures, pattern matching, and closures. It interoperates seamlessly with existing Java code and libraries.
I used these slides for a Scala workshop that I gave. They are based on these: http://www.scala-lang.org/node/4454. Thanks to Alf Kristian Støyle and Fredrik Vraalsen for sharing!
Scala Intro training @ Lohika, Odessa, UA.
This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.
An Introduction to Scala for Java DevelopersMiles Sabin
The document provides an introduction to Scala for Java developers. It outlines key features of Scala including cleaning up Java syntax, going beyond Java with features like case classes, traits, and pattern matching, and its functional focus including support for higher-order functions, the Option type, and for comprehensions. The document also briefly discusses the Scala IDE for Eclipse.
Solid and Sustainable Development in Scalascalaconfjp
Kazuhiro Sera introduced several of his Scala projects including ScalikeJDBC, Skinny Framework, and AWScala. He discussed some of his philosophies for solid and sustainable development in Scala including using simplified class-based OOP with immutable data structures, avoiding overkill abstraction, writing tests without question, keeping infrastructure lightweight, and ensuring projects have no surprises for newcomers. He welcomed questions during the upcoming AMA session.
Scala is a multi-paradigm language that runs on the JVM and interoperates with Java code and libraries. It combines object-oriented and functional programming by allowing functions to be treated as objects and supports features like traits, pattern matching, and immutable data structures. The Scala compiler infers types and generates boilerplate code like getters/setters, making development more productive compared to Java. While Scala has a learning curve, it allows a more concise and scalable language for building applications.
This document provides an overview of the Scala programming language and discusses its usage on Android. Scala is a multi-paradigm language that integrates object-oriented and functional programming. It runs on the Java Virtual Machine and is used by companies like LinkedIn, Twitter, and The Guardian. Scala's features include being object-oriented, functional, statically typed, and expressive while allowing concise code. It supports classes, traits, pattern matching, and lazy evaluation among other things.
Functional Objects & Function and ClosuresSandip Kumar
Scala functions are objects that implement traits like Function1. Functions are treated as objects with an apply method. When a function is defined as a method in a class, it is treated differently than a standalone function. Functions can take variable arguments using a * notation and have default parameter values specified.
Scaladroids: Developing Android Apps with ScalaOstap Andrusiv
Android is a fast-growing mobile operating system with millions of users worldwide.
Scala is a modern programming language designed to express common programming patterns in a concise, elegant, and type-safe way. Why not combine both of them?
This document provides an overview of Scala fundamentals including:
- Scala is a programming language for the JVM that supports both object-oriented and functional paradigms.
- It defines variables, values, lazy values, functions, types, classes, objects, traits, and higher-order functions.
- Classes can extend other classes and traits, allowing for multiple inheritance. Objects are used as singletons.
- Functional concepts like immutability, anonymous functions, and higher-order functions are supported.
Slides from my talk at the Feb 2011 Seattle Tech Startups meeting. More info here (along with powerpoint slides): http://www.startupmonkeys.com/2011/02/scala-frugal-mechanic/
Short (45 min) version of my 'Pragmatic Real-World Scala' talk. Discussing patterns and idioms discovered during 1.5 years of building a production system for finance; portfolio management and simulation.
The document summarizes the agenda and content of a Scala training workshop. The agenda includes functions and evaluations, higher order functions, data and abstraction, and exercises. Key points from the document include:
- Functions can be defined conditionally and with value definitions. Blocks allow grouping of definitions and expressions. Tail recursion optimizes recursion by reusing the call stack.
- Higher order functions allow functions to be passed as parameters or returned as results. Currying transforms functions that take multiple parameters into chains of functions that each take a single parameter.
- Classes define hierarchies and traits provide flexibility for code reuse like interfaces while abstract classes are used for base classes requiring constructor arguments.
- Exercises include implementing
This document introduces Scala and its key features. Scala is a JVM language that combines object-oriented and functional programming. It allows for concise code through features like type inference, method declaration simplification, and pattern matching. Scala supports both object-oriented concepts like classes and traits as well as functional programming with immutable data structures and higher-order functions. It also builds in support for concurrency through its Actor model. In summary, Scala aims to make code more concise while enabling functional and concurrent programming on the JVM.
Martin Odersky discusses the past, present, and future of Scala over the past 5 years and next 5 years. Key points include:
- Scala has grown significantly in usage and community over the past 6 years since its first release.
- Scala 2.8 will include improvements like new collections, package objects, named/default parameters, and better tool support.
- Over the next 5 years, Scala will focus on improving concurrency and parallelism through better abstractions, analyses, and static typing support.
The document discusses Scala, a programming language designed to be scalable. It can be used for both small and large programs. Scala combines object-oriented and functional programming. It interoperates seamlessly with Java but allows developers to add new constructs like actors through libraries. The Scala community is growing, with industrial adoption starting at companies like Twitter.
Introduction to Functional Programming with Scalapramode_ce
The document provides an introduction to functional programming with Scala. It outlines the following topics that will be covered: learning Scala syntax and writing simple programs; important functional programming concepts like closures, higher-order functions, purity, lazy evaluation, currying, tail calls, immutability, and type inference; and understanding the functional programming paradigm through Scala. It also provides some background information on Scala and examples of Scala code demonstrating various concepts.
Scala is a modern programming language created by Martin Odersky that provides static typing and supports both object-oriented and functional programming paradigms. It compiles to Java bytecode and runs on the Java Virtual Machine (JVM), allowing it to interoperate with Java. Many consider Scala to be a better alternative to Java due to its concise and expressive syntax. Scala sees widespread use in production systems and has growing job opportunities for developers with Scala skills.
Sous ce nom de session trollesque se cache une présentation de l'outil SBT. L'idée est de mettre en avant ce que SBT peut apporter en plus dans le quotidien du développeur comparé aux outils reconnus tel que maven.
Nous parlerons ici de son utilisation au sein de projets Java même s'il s'est développé conjointement avec le scala. Durant cette présentation, nous verrons les fonctionnalités clefs qui pourront influencer vos choix sur vos projets.
This document summarizes key features of the Scala programming language. Some key points include:
- Scala runs on the Java Virtual Machine (JVM) and allows for type inference, immutable values, functional programming patterns like pattern matching, and object-oriented features like traits for inheritance.
- Scala favors immutable values over mutable variables for scalability. Features like actors allow for concurrency without shared mutable state.
- Scala code can be compiled to JavaScript using Scala.js, allowing full-stack development in a single language.
- Traits provide a powerful way to do multiple inheritance by combining traits and classes at runtime.
Introduction à Scala - Michel Schinz - January 2010JUG Lausanne
Scala is a programming language that combines object-oriented and functional programming. It runs on the JVM and is interoperable with Java. Scala is statically typed and concise.
Scala allows modeling of concepts like rational numbers and mutable cells. Classes can implement traits to mix in functionality like logging. Pattern matching makes deconstructing data structures like lists and optional values easy. The Scala library includes collections, functions, and other functional programming constructs.
Scala is a statically typed programming language that runs on the Java Virtual Machine and interoperates seamlessly with Java. It unifies object-oriented and functional programming in one concise, high-level language. The presentation demonstrated Scala's powerful and lightweight syntax through examples of object-oriented code, collections, parallel programming and a game of life simulation, encouraging questions from the audience.
This document provides an introduction to functional programming and the Scala programming language. It discusses core concepts of functional programming like immutable data, pure functions, expressions over instructions, and first-class functions. It provides examples comparing imperative Java code to equivalent functional Scala code. The document also outlines benefits of functional programming like simpler concurrency, optimizations, easier debugging, and cleaner code. It concludes by providing additional resources for learning Scala and functional programming.
Knoldus organized a Meetup on 1 April 2015. In this Meetup, we introduced Spark with Scala. Apache Spark is a fast and general engine for large-scale data processing. Spark is used at a wide range of organizations to process large datasets.
Hammurabi is an internal domain-specific language (DSL) for rule-based programming implemented in Scala. It allows domain experts to write rules in plain Scala code without learning a new language. Rules are evaluated by a rule engine that executes matching rules on a working memory of facts. The DSL aims to be readable, flexible and leverage Scala features like autocompletion. It also supports priorities, selecting objects, and exiting or failing evaluation. The architecture uses actors for concurrent rule evaluation. Future work includes improving performance using RETE algorithm and providing alternative selection methods.
This document provides an introduction and overview of the Scala programming language. It discusses how Scala is a scalable language that is pure object-oriented, statically typed, functional, and runs on the JVM. It highlights some of Scala's key features like everything being an object, no primitive types, and operations being method calls. Motivations for using Scala over Java are presented, including support for functions and closures, an extended type system, and properties of essence over ceremony and extended control structures.
Mémoire de fin d'étude - La big data et les réseaux sociauxChloé Marty
Comment l’explosion quantitative de la data va donner aux marques l’opportunité de mieux cibler et de mieux s’adresser à leurs publics sur les réseaux sociaux alors que l’utilisation et l’exploitation de ces données s’avère être très complexe et pose un problème d’éthique ?
The document contains a project submission form and report for a Certified Organizational Development Analyst program. It includes an analysis of the fictional organization Universal Workplace Solutions using the 6-Box Model and Value Discipline tools. It also contains an HR audit using the People Capability Maturity Model. The report analyzes the organization's structure, relationships, rewards, leadership, and processes to identify areas for improvement as the company plans for global expansion by 2020. A questionnaire was distributed to employees to understand their perspectives. The analysis and audit findings will help the organization strengthen its internal environment and capabilities to achieve its strategic goals.
Faster and more confident diagnosis:
• True anatomical details
• Distortion free images, 1:1 anatomical accuracy • Eliminate doubts from 2D exams
Predictability in surgery, improved treatment quality Increased productivity and autonomy
• In-office 3D exams– limit patient visits Improved communication
• Show patients images that are easier to understand Increased treatment plan acceptance.
The advantages at a glance
• Affordable three-in-one solution– 3D, 2D panoramic and optional cephalometric imaging
• Highest resolution (76 μm), low dose 3D images
• Flexible 3D programs– from local exams to full-arch exams
• Compatible with guided surgery systems
Démystifions le machine learning avec spark par David Martin pour le Salon B...Ippon
Les volumes de données permettent d’envisager de nouveaux usages, pour la plupart rendus accessibles grâce aux algorithmes de Machine Learning. Découvrez ce qu’est le Machine Learning par de multiples exemples. Comprenez les enjeux autour de la donnée et comment passer de la donnée brute aux prédictions en identifiant les différentes étapes intermédiaires. Enfin, découvrez comment mettre ces concepts en oeuvre avec une présentation des outils à disposition aujourd’hui, et un focus sur Spark, son architecture et les possibilités offertes autour du Machine Learning.
BCS SPA 2010 - An Introduction to Scala for Java DevelopersMiles Sabin
This document provides an introduction to Scala for Java developers. It outlines how Scala cleans up Java syntax by making semi-colons optional, using == for equals and eq for reference equality, and allowing periods to be omitted. It also describes how Scala goes beyond Java by supporting features like case classes, pattern matching, named and default arguments, and mixin composition with traits. The document provides examples of using these features and explains how Scala seamlessly interoperates with Java.
A Brief Introduction to Scala for Java DevelopersMiles Sabin
Scala is a programming language that blends object-oriented and functional programming styles. It is designed to interoperate with Java code and runs on the Java Virtual Machine. Some key features of Scala include case classes, pattern matching, traits for mixing functionality, and immutable data structures. Scala code compiles to Java bytecode, allowing seamless use of Java libraries and tools.
Miles Sabin Introduction To Scala For Java DevelopersSkills Matter
Scala is a programming language that blends object-oriented and functional programming styles. It is designed to interoperate with Java code and runs on the Java Virtual Machine. Some key features of Scala include case classes, pattern matching, traits for mixing behavior, and immutable data structures. Scala code compiles to Java bytecode, allowing seamless use of Java libraries and tools.
The document provides an overview of the Scala programming language. It begins with an agenda that outlines topics like differences between Java and Scala, Scala data types, variables, classes, functions, closures, exception handling and collections. It then discusses specific aspects of Scala like verbosity reduction compared to Java, functional programming influences, object-oriented features, interoperability with Java and compilation to Java bytecode. Examples are provided to illustrate Scala concepts like functions, classes, recursion, higher-order functions and exception handling. The document aims to explain Scala and reasons for differences from Java.
Scala is a multi-paradigm programming language designed to express common programming patterns in a concise, elegant, and type-safe way. It is designed to integrate features of object-oriented and functional languages. Some key features of Scala include object-oriented programming, strong static typing, functional programming, pattern matching, actor-based concurrency, and more.
This presentation was presented at OSS camp in New Delhi. It deals with the basics of Scala language and how we can use it to build scalable Applications
Qcon2011 functions rockpresentation_scalaMichael Stal
Scala functions provide powerful ways to decompose problems and harness the benefits of functional programming. The presentation introduces core concepts of functional programming using Scala as an example language, highlighting how Scala combines object-oriented and functional programming. It presents benefits like immutability, higher-order functions, and improved concurrency while avoiding past performance issues through modern virtual machines and libraries.
There are many programming languages that can be used on the JVM (Java, Scala, Groovy, Kotlin, ...). In this session, we'll outline the main differences between them and discuss advantages and disadvantages for each.
Scala: Object-Oriented Meets Functional, by Iulian Dragos3Pillar Global
A presentation from Iulian Dragos of Typesafe that gives an overview of the Scala programming language. The presentation was given at a Functional Angle conference in Timisoara, Romania sponsored by 3Pillar. Iulian Dragos has been working on Scala since 2004. He currently works for Typesafe, a start-up that was co-founded by Scala’s creator, Martin Odersky.
This document provides an overview of Clojure and why one may want to try it. Some key points include:
- Clojure is a functional programming language that runs on the JVM and allows easy interoperability with Java.
- It has a very small and elegant syntax based on Lisp with sensible macro names and prefix notation.
- Clojure encourages pure functional programming and the use of immutable data structures, while providing tools like Software Transactional Memory to allow safe mutable state changes.
- Its focus on functions as first-class citizens and referential transparency can provide benefits for writing parallel and concurrent code more easily compared to other languages.
Scala is a powerful language for the JVM that is compatible with JDK 1.5+. It is a functional language maintained by Typesafe along with the community. Scala compiles to JVM bytecode like Java but has features like objects, traits, pattern matching and functional programming. James Gosling, the creator of Java, said that if he were to pick a language other than Java today, it would be Scala.
This document provides an introduction to Scala concepts and features compared to Java, including how to set up Scala, the Simple Build Tool (SBT), case classes, lazy definitions, imports, objects, pattern matching, collections, higher-order functions, partial functions, currying, implicit conversions, and implicit parameters. Useful Scala resources are also listed.
This document provides an overview of the Scala programming language, including what it is, its toolchain, basic syntax examples comparing it to Java, built-in support for XML, actors, and advantages and disadvantages. Scala is an object-functional language that runs on the JVM and is intended to be a "better Java". It has features like XML support, an actor model for concurrency, and combines object-oriented and functional programming paradigms, but its ecosystem and compiler can be slow and syntax for some functional features is verbose.
This document provides an introduction to Scala for Java developers. It discusses that Scala is a hybrid object-oriented and functional language that runs on the JVM and interoperates well with Java. It highlights several features of Scala that allow for more concise code compared to Java, such as type inference, expressions instead of statements, higher-order functions, and case classes.
The document provides an overview of key Java concepts including:
1) Classes and methods define the structure and behaviors of objects in Java. Data types include primitives and object references.
2) Control statements like if/else and loops operate similarly to other languages like C++. Object-oriented concepts include inheritance, polymorphism, and encapsulation.
3) Interfaces define common behaviors without implementation, while abstract classes can contain abstract and implemented methods. The Java Virtual Machine executes Java bytecode making programs platform independent.
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLabCloudxLab
Scala is a modern multi-paradigm programming language that integrates features of object-oriented and functional programming. It is statically typed, has a lightweight syntax, and compiles to Java bytecode so it can use Java libraries. Scala source code is compiled to Java bytecode using the Scala compiler and runs on the Java Virtual Machine. Common data structures in Scala include collections like lists, arrays, sets and maps. Scala supports higher-order functions, immutable data, pattern matching and case classes. Build tools like SBT are used to manage Scala projects.
Ardra Nakshatra (आर्द्रा): Understanding its Effects and RemediesAstro Pathshala
Ardra Nakshatra, the sixth Nakshatra in Vedic astrology, spans from 6°40' to 20° in the Gemini zodiac sign. Governed by Rahu, the north lunar node, Ardra translates to "the moist one" or "the star of sorrow." Symbolized by a teardrop, it represents the transformational power of storms, bringing both destruction and renewal.
About Astro Pathshala
Astro Pathshala is a renowned astrology institute offering comprehensive astrology courses and personalized astrological consultations for over 20 years. Founded by Gurudev Sunil Vashist ji, Astro Pathshala has been a beacon of knowledge and guidance in the field of Vedic astrology. With a team of experienced astrologers, the institute provides in-depth courses that cover various aspects of astrology, including Nakshatras, planetary influences, and remedies. Whether you are a beginner seeking to learn astrology or someone looking for expert astrological advice, Astro Pathshala is dedicated to helping you navigate life's challenges and unlock your full potential through the ancient wisdom of Vedic astrology.
For more information about their courses and consultations, visit Astro Pathshala.
(T.L.E.) Agriculture: Essentials of GardeningMJDuyan
(𝐓𝐋𝐄 𝟏𝟎𝟎) (𝐋𝐞𝐬𝐬𝐨𝐧 𝟏.𝟎)-𝐅𝐢𝐧𝐚𝐥𝐬
Lesson Outcome:
-Students will understand the basics of gardening, including the importance of soil, water, and sunlight for plant growth. They will learn to identify and use essential gardening tools, plant seeds, and seedlings properly, and manage common garden pests using eco-friendly methods.
How to Show Sample Data in Tree and Kanban View in Odoo 17Celine George
In Odoo 17, sample data serves as a valuable resource for users seeking to familiarize themselves with the functionalities and capabilities of the software prior to integrating their own information. In this slide we are going to discuss about how to show sample data to a tree view and a kanban view.
Join educators from the US and worldwide at this year’s conference, themed “Strategies for Proficiency & Acquisition,” to learn from top experts in world language teaching.
Front Desk Management in the Odoo 17 ERPCeline George
Front desk officers are responsible for taking care of guests and customers. Their work mainly involves interacting with customers and business partners, either in person or through phone calls.
Integrated Marketing Communications (IMC)- Concept, Features, Elements, Role of advertising in IMC
Advertising: Concept, Features, Evolution of Advertising, Active Participants, Benefits of advertising to Business firms and consumers.
Classification of advertising: Geographic, Media, Target audience and Functions.
Beyond the Advance Presentation for By the Book 9John Rodzvilla
In June 2020, L.L. McKinney, a Black author of young adult novels, began the #publishingpaidme hashtag to create a discussion on how the publishing industry treats Black authors: “what they’re paid. What the marketing is. How the books are treated. How one Black book not reaching its parameters casts a shadow on all Black books and all Black authors, and that’s not the same for our white counterparts.” (Grady 2020) McKinney’s call resulted in an online discussion across 65,000 tweets between authors of all races and the creation of a Google spreadsheet that collected information on over 2,000 titles.
While the conversation was originally meant to discuss the ethical value of book publishing, it became an economic assessment by authors of how publishers treated authors of color and women authors without a full analysis of the data collected. This paper would present the data collected from relevant tweets and the Google database to show not only the range of advances among participating authors split out by their race, gender, sexual orientation and the genre of their work, but also the publishers’ treatment of their titles in terms of deal announcements and pre-pub attention in industry publications. The paper is based on a multi-year project of cleaning and evaluating the collected data to assess what it reveals about the habits and strategies of American publishers in acquiring and promoting titles from a diverse group of authors across the literary, non-fiction, children’s, mystery, romance, and SFF genres.
Webinar Innovative assessments for SOcial Emotional SkillsEduSkills OECD
Presentations by Adriano Linzarini and Daniel Catarino da Silva of the OECD Rethinking Assessment of Social and Emotional Skills project from the OECD webinar "Innovations in measuring social and emotional skills and what AI will bring next" on 5 July 2024
Beginner's Guide to Bypassing Falco Container Runtime Security in Kubernetes ...anjaliinfosec
This presentation, crafted for the Kubernetes Village at BSides Bangalore 2024, delves into the essentials of bypassing Falco, a leading container runtime security solution in Kubernetes. Tailored for beginners, it covers fundamental concepts, practical techniques, and real-world examples to help you understand and navigate Falco's security mechanisms effectively. Ideal for developers, security professionals, and tech enthusiasts eager to enhance their expertise in Kubernetes security and container runtime defenses.
How to Configure Time Off Types in Odoo 17Celine George
Now we can take look into how to configure time off types in odoo 17 through this slide. Time-off types are used to grant or request different types of leave. Only then the authorities will have a clear view or a clear understanding of what kind of leave the employee is taking.
2. In this presentation:
● Motivation and History
● Meet Scala
● Simple data structures and loops
● Objects
● Types and Generics
● Advanced topics
● Conclusions and references
3. In this presentation:
● Motivation and History
● Meet Scala
● Simple data structures and loops
● Objects
● Types and Generics
● Advanced topics
● Conclusions and references
4. Java Architecture
HelloWorld.java
javac
HelloWorld.class
load class Java Virtual Machine
Java Class Garbage
Libraries Loader Collector
Bytecode Executor JIT
HotSpot
compiler
interpret execute
Native OS
5. Java as a Platform
HelloWorld.****
****c
HelloWorld.class
load class
Java Virtual Machine
Java Class Garbage
Libraries Loader Collector
...
7. Why JVM?
● Most popular VM in the world
● Multi-platform
● Free
● Mature
● Secure and reliable
● Fast
can outperform native code compiled with GCC
● Management and monitoring capabilities
● Has a specification
– multiple vendor and open source implementations
8. Why Scala?
● Object oriented and functional
● Statically typed
● High performance
● High interoperability with Java
● Advanced type system
● Advanced concurrency model
● Support for modularity and extensibility
● Built-in XML support
9. Java and Scala History
Java
Java 1.1
announced, 1997
first beta Java Java 1.5 Java 1.6
J. Gosling release 1.0 Java 1.2 Java 1.3 Java 1.4 (Tiger) (Mustang)
1991 1995 1996 1998 2000 2002 2004 2006
GJ
1999
work on
Scala
M. Odersky starts
1995 1999 2001 1.0 2003 2.0 2006
10. In this presentation:
● Motivation and History
● Meet Scala
● Simple data structures and loops
● Objects
● Types and Generics
● Advanced topics
● Conclusions and references
11. Hello Scala
object HelloWorld extends Application { ● object = singleton class
● optional semicolon
println("Hello, world!")
● def
} ● implicit public
● type after name, optional
object HelloWorld { ● generics using [ ]
def main(args: Array[String]) = Unit =
: ● unit = void
System.out.println("Hello, world!") ● calling into java.lang
library
} ● different constructor
syntax
12. Simple Greeting
def main(args:Array[String]) = {
immutable variable
val size = args.length type int inferred
println("Greeting " + size + " members:")
mutable variable
var greeting = "Hello " type String int is an object,
inferred alternative method
for (i <- 0 until args.length) {
invocation syntax
greeting += (args(i) + ",") Java-like
loop
} array element access
if (args.length > 0) greeting = greeting.substring(0, greeting.length – 1)
greeting += "!" if statement
println(greeting);
}
13. Simple Timer
object SimpleTimer { function type
def oncePerSecond(callback: () => unit) {
while (true) { callback(); Thread.sleep(1000) }
}
def timeFlies() {
println("time flies like an arrow...")
}
def main(args: Array[String]) {
functions are objects
oncePerSecond(timeFlies)
}
}
15. Better Greeting
def main(args:Array[String]) = {
val size = args.length
println("Greeting " + size + " members:")
var greeting = "Hello "
for (i <- 0 until args.length) {
greeting += (args(i) + ",")
args.foreach(arg => greeting += (arg + " "))
}
if (args.length > 0) greeting = greeting.substring(0, greeting.length – 1)
greeting += "!"
println(greeting);
}
16. In this presentation:
● Motivation and History
● Meet Scala
● Simple data structures and loops
● Objects
● Types and Generics
● Advanced topics
● Conclusions and references
17. Tuples
def divmod(x: int, y: int) = (x / y, x % y)
val z = divmod(x, y)
println("quotient: " + z._1 + ", rest: " + z._2)
The actual type of a tuple depends upon the number and of
elements it contains and the types of those elements.
The type of (99, "Luftballons") is Tuple2[Int, String].
The type of ('u', 'r', "the", 1, 4, "me") is
Tuple6[Char, Char, String, Int, Int, String]
18. Map
val treasureMap = new HashMap[Int, String]
treasureMap += 1 -> "Go to island."
treasureMap += 2 -> "Find big X on ground."
treasureMap += 3 -> "Dig."
println(treasureMap(2))
When we say 1 -> "Go to island.", we are actually calling a method named ->
on an Int with the value 1, and passing in a String with the value "Go to island."
This -> method, which you can invoke on any object in a Scala program,
returns a two-element tuple containing the key and value.
val romanNumeral = Map(1 -> "I", 2 -> "II",
3 -> "III", 4 -> "IV", 5 -> "V")
println(romanNumeral(4))
19. Comprehensions
val filesHere = (new java.io.File(".")).listFiles
for (
file <- filesHere;
if file.isFile; Types with no typing!
if file.getName.endsWith(".scala")
) println("Found " + file)
val names = "Ted Neward" :: "Neal Ford" :: "Scott Davis" :: "Venkat
Subramaniam" :: "David Geary" :: Nil
val longFirstNames = for {
name <- names
firstName = name.substring(0, name.indexOf(' '))
if firstName.length > 4
} yield firstName
20. Comprehensions defined
Example: for (val p ← persons; p.age > 20) yield p.name
Generally, a for-comprehension is of the form
for ( s ) yield e
s is a sequence of generators, definitions and filters
generator is of the form val x ← e,where e is a list-valued
expression; it binds x to successive values in the list
definition is of the form val x = e; it introduces x as a name
for the value of e in the rest of the comprehension
filter is an expression f of type boolean; it omits from
consideration all bindings for which f is false
22. Basic pattern matching
Scala case statements can’t “overlap” causing
multiple matches
Match statement returns whatever value is
returned from the matched case statement
23. In this presentation:
● Motivation and History
● Meet Scala
● Simple data structures and loops
● Objects
● Types and Generics
● Advanced topics
● Conclusions and references
24. Everything is an object
● Scala uses a pure object-oriented model
similar to Smalltalk: every value is an object
and every operation is a message send.
● Every class in Scala inherits from scala.Any
● The classes fall into two categories:
– value classes inherit from scala.AnyVal and
– reference classes inherit from scala.AnyRef
26. Null and Nothing
● Type Null is a subtype of all reference types; its
only instance is the null reference.
Since Null is not a subtype of value types, null is not a
member of any such type. For instance, it is not
possible to assign null to a variable of type int.
● Type Nothing is a subtype of every other type;
there exist no instances of this type.
For instance, the Scala library defines a value Nil of type
List[Nothing]. Because lists are covariant in Scala,
this makes Nil an instance of List[T], for any
element type T.
28. Simple property and
default constructor
Java: Scala:
public class Person { (var name: String)
class Person {
private String name = null; var name: String
public Person(String name) { }
this.name = name;
} ...
public String getName() { println(person.name)
return name;
}
public void setName(String name) {
this.name = name;
}
}
29. Constructors, operators,
overriding methods
class Rational(n:Int, d:Int) { Default
constructor
private def gcd(x:Int, y:Int): Int = {
...//greatest common denominator
} Object initialization uses
private val g = gcd(n,d) constructor properties,
read-only properties defined
val numer:Int = n/g
val denom:Int = d/g Alternative constructor;
def this(n:Int) = { this(n, 1) } must call the default constructor
def +(that:Rational) = new Rational(numer*that.denom + that.numer*denom,
denom * that.denom)
def -(that:Rational) = ... Operators
def *(that:Rational) = ... defined
def /(that:Rational) = ...
override def toString() = "Rational: [" + numer + " / " + denom + "]"
} Override method –
override modifier is mandatory
30. Abstract class
abstract class Shape {
var fillColor:Color = null Property
def draw(g:Graphics):Unit Abstract
methods
def area:Double
}
32. Advanced Properties
Effectively, all public variables are instance properties.
To override mutator and accessor behavior:
_= method suffix
syntax allows
to redefine the
assignment
operator for a
variable
33. Simulating a Java Bean
class Person(fn:String, ln:String, a:Int) {
@scala.reflect.BeanProperty var firstName = fn
@scala.reflect.BeanProperty var lastName = ln
@scala.reflect.BeanProperty var age = a
override def toString =
"[Person firstName:" + firstName + " lastName:"
+ lastName + " age:" + age + " ]"
}
34. More on Methods
● Protected and private, packages
– public by default
– protected and private modifiers supported
– private[<package name>] enhanced “package protected” -
applies to one of the containing packages of current method
● Returning from method
– return statement is optional: the last statement in an expression,
be it a scope, a closure or a method becomes its return value.
– If method can return at different points in the execution flow, return
type must be specified
● Repeated parameters (var-args) - <method>(...,<arg>*)
● Method reference
– call without parameters or prefix with &
35. Advanced Objects
● Singletons and companions
● Object as a function
● Case classes
● Sealed classes
● Traits and mix-in class composition
● Implicit conversions (views)
● More...
36. Singleton classes and
pseudo-static methods
● class vs. object (Singleton design pattern)
● companions
object Person { //companion module
def createPerson() = new Person()
}
class Person { //companion class
def name() = "Daniel"
}
37. Function Object
Function object has one or more apply methods:
object Square {
def apply(in: double) = in * in
def apply(in: float) = in * in
def apply(in: int) = in * in
} val xSquared = Square(x) Doug Pardee
Together with companion object feature, it is used to
facilitate the Factory Method design pattern, as we saw
in previous Map example:
val romanNumeral = Map(1 -> "I", 2 -> "II", 3 -> "III",
4 -> "IV", 5 -> "V")
38. ADTs Using Case Class
● Case classes export their constructor parameters and
provide a recursive decomposition mechanism via
pattern matching. The constructor parameters of
case classes are treated as public values and can be
accessed directly.
● The new keyword is optional for instance creation.
case class ClockTime (hour: Int, min: Int)
is a valid case class definition.
ClockTime(10,30) creates an instance.
It makes only sense to define case classes if pattern matching is
used to decompose data structures.
39. Case Class - Example
The output will look something like this:
Red: 100
Blue: 220
R: 100, G: 200, B: 50
Invalid color
40. Another Case Class
Set of definitions for binary tree:
In-order traversal of binary tree:
41. Case classes defined
● All lower-case identifiers in the pattern will bind the decomposed
value and are available on the right-hand side of the pattern.
● Order is important: a first-match policy is used.
● Constant values can be used in patterns to restrict matching case
ClockTime(10, min) will only match any time in the 10th hour (and
bind minutes to min)
● Richer conditions can be defined with guards.
– case ClockTime(hour, min) if hour > min
● When no pattern matches a value, the match statement throws a
MatchError.
● A default case can be added, using the wild-card pattern. case _ will
match any value.
42. Exception handling
Exception handling uses “almost Java” syntax with pattern match on
exception type within the catch clause.
Side note: Scala does not have checked exceptions, in contrast to Java.
43. Sealed classes
Sealed classes are defined using the sealed modifier.
A sealed class may not be directly inherited, except if the
inheriting template is defined in the same source file as
the inherited class*.
In case of pattern match on sealed class, the compilation
will emit warnings if the set of patterns is not exhaustive
(MatchError might be raised at run-time)
44. Traits and
Mixin Class Composition
● Trait is a special kind of class defined using trait keyword
● Traits are like Java interfaces, but can define default
implementations for methods in the trait. A class can
incorporate as many traits as desired using with
keyword, accumulating their implementations.
● A trait can be inherited
– when defining a class
class JamesBondsCar extends Car with Flying with Diving
– or when creating an instance
val jbsCar = new Car with Flying with Diving
46. Traits – more details
● There must be a common parent class with the
inherited
● When multiple traits are inherited
– they can refer to members of their common super class,
– but not to members of other mixed-in traits.
● A trait can require another class or trait; it can only be
mixed-in when the requirement is available.
trait Reading extends Person requires Seeing
trait Reading extends Person { self: Seeing => ... }
● In contrast to classes, traits may not have constructor
parameters.
47. Mixins
He who defs last, defs best
The order in which traits are mixed-in determines overriding strategy
“Expression problem” example:
trait Base { trait BasePlus extends Base {
type exp <: Exp; class Plus(l: exp, r: exp) extends Exp {
trait Exp { val left = l; val right = r;
def eval: int def eval = left.eval + right.eval
} }
class Num(v: int) extends Exp { }
val value = v; trait BaseNeg extends Base {
def eval = value class Neg(t: exp) extends Exp {
} val term = t;
} def eval = - term.eval;
}
}
trait Show extends Base { trait BasePlusNeg extends BasePlus with BaseNeg;
type exp <: Exp;
trait Exp extends super.Exp { trait ShowPlusNeg extends BasePlusNeg with Show {
def show: String; class Plus(l: exp, r: exp) extends
} super.Plus(l, r) with Exp {
class Num(v: int) extends def show = left.show + "+" + right.show;
super.Num(v) with Exp { }
def show = value.toString(); class Neg(t: exp) extends super.Neg(t) with Exp {
} def show = "-(" + term.show + ")";
} }
}
48. Traits – back to HelloWorld
object HelloWorld extends Application {
println("Hello, world!")
}
Surprise: Application is a trait!
● The main() method of the Application trait provides the ubiquitous entry point for
Java applications
● Since Application is a trait, the method actually "shows up" on the subclass
(HelloWorld).
● To execute this method, it is necessary to create the HelloWorld singleton, which
means constructing an instance of HelloWorld, which means "playing" the body of
the class, which effectively executes the application.
● Only after that is complete does the trait's main() get invoked
49. Implicit conversions (views)
Scala allows to define special methods which take a value
of a certain type (B) in as a parameter and return a value of
a different type (A) as the result. By marking this method
implicit, you tell the compiler to automatically use this
conversion in situations where a value of type A is called
for but a value of type B was passed.
implicit def str2int(str:String):Int = Integer.parseInt(str)
def addTwo(a:Int, b:Int) = a + b
addTwo("123", 456)
50. Implicit conversions -
usage example
Adding methods to classes.
Back to the loop we saw: for (i <- 0 until args.length) ...
=
val range = 0.until(args.length)
for (i <- range) ...
Where does method until come from?
scala.runtime.RichInt
How does 0:Int become a RichInt?
scala.Predef has
implicit def intWrapper(x:Int):RichInt = new RichInt(x)
51. Advanced classes and
methods
Packages and imports
Richer import syntax, import anywhere in the code
Implicit parameters
If implicit object of matching type is found “in scope” it can
replace a missing parameter
Inner classes and nested functions
inner classes are per instance, unlike in Java
Operators
any method can be used as infix operator
Currying
when a method is called with a fewer number of parameters, this will
yield a function taking the missing parameters as its arguments.
52. In this presentation:
● Motivation and History
● Meet Scala
● Simple data structures and loops
● Objects
● Types and Generics
● Advanced topics
● Conclusions and references
53. Generics
Scala Generics are erased after compilation, just like in Java.
abstract class TreeSet[A] { The contains and incl methods
def incl(x: A): TreeSet[A]; compare elements using methods < and >.
def contains(x: A): boolean; For an arbitrary type parameter we cannot
} guarantee it has these two methods.
We can enforce the comparability of a trait TreeSet[A <: Ordered[A]] {
type by demanding that it is a subtype def incl(x: A): TreeSet[A];
of Ordered trait. def contains(x: A): boolean;
}
In Java we need to do something like:
class TreeSet<T extends Comparable<? super T>>
A view bounded type parameter trait TreeSet[A <% Ordered[A]] {
clause [a <% T] only specifies that ...
the bounded type a must be }
convertible to the bound type T, using
an implicit conversion
54. Generics - Variance
Some Scala library collections are covariant (unlike Java)
Covariant sub-typing
class Stack[+a] { A covariant type parameter of a class may only appear in
covariant positions: values in the class, result types of
...
methods in the class, and type arguments to other covariant
} types, but not types of formal method parameters.
class Stack[+a] {
def push(x: a): Stack[a] =
^ covariant type parameter a
appears in contravariant position.
Using lower bounds, we can generalize the push method in Stack
class Stack[+a] {
def push[b >: a](x: b): Stack[b] = new NonEmptyStack(x, this)
Besides +, there is also a - prefix which indicates contra-variant subtyping.
object EmptyStack extends Stack[Nothing] { ... }
55. Advanced Generics
● Type variables abstract class Graph {
type Edge
type Node <: NodeIntf
● Self types abstract class NodeIntf {
def connectWith(node: Node): Edge
}
def nodes: List[Node]
def edges: List[Edge]
def addNode: Node
}
● Existential types (Java generics interoperability, wildcards)
T forSome {type Q}
Example: def m(x : T forSome {type T <: A}) = x is a
method that takes arguments that conform to T <: A, it can be
written also as def m(x: _ <: A) = x = Java's ? extends A
● Kinds - Generics of a Higher Kind (in progress)
56. In this presentation:
● Motivation and History
● Meet Scala
● Simple data structures and loops
● Objects
● Types and Generics
● Advanced topics
● Conclusions and references
57. Cool stuff:
Option and Either Monads
● Often a method needs to return either a value or nothing,
depending on various conditions (Haskell's Maybe)
● Option[A] is a sealed case class in the Scala core libraries
with 2 subclasses: Some(a:A) and None
● Either is another sealed case Either[A,B] with Left(a:A)
and Right(b:B) options
58. Cool stuff:
Structural types
● Structural typing offers the ability to reduce the scope of
polymorphism only over the subset of behaviors that need to be
common between the classes.
● Scala offers the benefit of both dynamic and statically typed
worlds through its implementation of structural typing - a compile
time checked duck typing.
59. Cool stuff:
Extractor objects
Paper: Matching Objects with Patterns
In Scala, patterns can be defined independently of case
classes. To this end, a method named unapply is
defined to yield a so-called extractor.
Extractor object:
object Twice {
def apply(x: Int): Int = x * 2
def unapply(z: Int): Option[Int] = if (z%2 == 0) Some(z/2) else None
}
object TwiceTest extends Application {
val x = Twice(21)
x match { case Twice(n) => println(n) } // prints 21
}
60. Cool stuff -
Concurrency & Actors
Paper: Event-Based Programming without Inversion of Control
● Moore's law has changed, we don’t get the same increase in clock
frequency as we used to, instead, we get more cores.
● Solve the problem by (re)writing software to be concurrent.
● Actors (programming model borrowed from Erlang) implemented as a Scala
library implements Message-Passing Concurrency rather than Shared-State
Concurrency (the scheme adopted by C, Java, C# etc.) Actors have no shared state and
are communicating by sending and receiving messages which makes it possible to write
code that is deterministic and side-effect-free.
● Unlike Erlang VM (BEAM) where process is very lightweight, Scala actor is
either thread-based or event based. Former is limited in number, latter can
block its OS thread.
● Erlang is a functional language - data is immutable, in Scala programmer
needs to take care of that alone.
● Scala is statically typed, while Erlang is dynamic
● Erlang uses tail recursion all the time, while Scala uses traditional iterations
(tail recursion in JVM is problematic)
● Erlang has built-in code hot-swapping capabilities, the possibilities for hot-
swapping in Scala are limited because of static typing
from Jonas Boner and Yariv Sadan
61. More cool stuff
● XML processing – native XML
● Monads
● Partial functions (isDefinedAt)
● Lazy values (lazy)
● Annotations (@)
● Parser combinators library
● ...
62. In this presentation:
● Motivation and History
● Meet Scala
● Simple data structures and loops
● Objects
● Types and Generics
● Advanced topics
● Conclusions and references
64. The power of Scala
operator = method = function = object
Scala supports several programming
paradigms off the shelf...
Functional programming: Object-oriented programming:
Makes it easy to build Makes it easy to adapt and
interesting things from extend
simple parts, using complex systems, using
- higher-order functions, - subtyping and inheritance,
- algebraic types and - dynamic configurations,
pattern matching, - classes as partial abstractions.
- parametric polymorphism.
65. “Scalable language”
...and allows the programmer to extend it
with completely new paradigms.
Programmer can define language constructs
def While (p: => Boolean) (s: => Unit) {
if (p) { s ; While(p)(s) }
}
66. Nobody's perfect...
● Language specification constantly changing
● Lack of proper reflection support
(undocumented)
● Not enough/inadequate documentation for
beginners
● Lacking proper IDE support
● Too many ways to do one thing, multi-
paradigm language problem (as in C++,
Perl) - can Scala really scale on LoC?
68. References
● Scala for Java refugees (Daniel Spiewak)
● The busy Java developer's guide to Scala (Ted Neward)
● Ricky Clarkson, David R. MacIver, Henrik Huttunen, Debasish Ghosh
● A tour of Scala and other resources on http://www.scala-lang.org/
● http://scala-blogs.org/
● Scala forums @ Nabble
● Scalazine @ Artima
● Programming in Scala (book) (M. Odersky, L. Spoon, B. Venners)
● Martin Odersky's Weblog
● The Scala Experiment (video) , JavaOne 2008 Scala (audio and slides)
● Scala APIs