The Scala programming language has been gaining momentum recently as an alternative (and some might say successor) to Java on the JVM. This talk will start with an introduction to basic Scala syntax and concepts, then delve into some of Scala's more interesting and unique features. At the end we'll show a brief example of how Scala is used by the Lift web framework to simplify dynamic web apps.
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!
The Scala programming language has been gaining momentum recently as an alternative (and some might say successor) to Java on the JVM. This talk will start with an introduction to basic Scala syntax and concepts, then delve into some of Scala's more interesting and unique features. At the end we'll show a brief example of how Scala is used by the Lift web framework to simplify dynamic web apps.
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!
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?
Scala is becoming the language of choice for many development teams. This talk highlights how Scala excels in the world of multi-core processing and explores how it compares to Java 8.
Video Presentation: http://youtu.be/8vxTowBXJSg
Scala Intro training @ Lohika, Odessa, UA.
This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.
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.
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.
Using Combine, SwiftUI and callAsFunction to build an experimental localizati...Donny Wals
Learn how to use Combine, SwiftUI and Swift 5.2's callAsFunction to build an experimental localization system and familiarize yourself with these new APIs in iOS 13.
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?
Scala is becoming the language of choice for many development teams. This talk highlights how Scala excels in the world of multi-core processing and explores how it compares to Java 8.
Video Presentation: http://youtu.be/8vxTowBXJSg
Scala Intro training @ Lohika, Odessa, UA.
This is a basic Scala Programming Language overview intended to evangelize the language among any-language programmers.
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.
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.
Using Combine, SwiftUI and callAsFunction to build an experimental localizati...Donny Wals
Learn how to use Combine, SwiftUI and Swift 5.2's callAsFunction to build an experimental localization system and familiarize yourself with these new APIs in iOS 13.
Kotlin: forse è la volta buona (Trento)Davide Cerbo
Il codice di esempio e disponibile qui: https://github.com/jesty/kotlin-fossavotabona
La variazione col DAO al posto del repository è disponibile qui:
https://github.com/jesty/kotlin-fossavotabona/tree/dao-companion-object
The things we don't see – stories of Software, Scala and AkkaKonrad Malawski
Opening keynote for Scalapeno, Tel Aviv 2016.
The talk focuses and explains the things we don't often see explicitly and/or don't notice when doing our daily work, yet make up a large part of the ecosystem and maturity of the ecoststem as a whole. We also dive into some of the more confusing bits around using the same word about different things in software
Davide Cerbo - Kotlin: forse è la volta buona - Codemotion Milan 2017 Codemotion
Dopo 20 anni Java inizia a sentire il peso degli anni e la sua sintassi non evolve come vorremmo, ma la JVM resta sempre un ambiente affidabile ed è già in produzione presso moltissime aziende. Negli ultimi anni sono usciti molti linguaggi basati sulla JVM, ma non tutti hanno avuto il successo sperato. Kotlin ha conquistato Android e, ora, grazie a una sintassi intuitiva e grandi aziende che lo supportano potrebbe essere molto utilizzato anche nelle applicazioni web. Durante il talk vedremo le basi del linguaggio e come sviluppare una applicazione web pronta ad andare in produzione.
This is an introductory SCALA workshop for a JAVA developer. Hence, we're going to explore 'functional' side of the language. SCALA is 50% OOP (Object-Oriented-Programming) and 50% FP (Functional-Programming). Main principles of FP are discussed, such as: tail-recursion, currying, pure-functions, lazy evaluation etc.) along with some examples in code.
We look at the basic keywords and constructs in SCALA.
In the end SCALA tools which are helpful for developers are listed.
UiPath Test Automation using UiPath Test Suite series, part 4DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 4. In this session, we will cover Test Manager overview along with SAP heatmap.
The UiPath Test Manager overview with SAP heatmap webinar offers a concise yet comprehensive exploration of the role of a Test Manager within SAP environments, coupled with the utilization of heatmaps for effective testing strategies.
Participants will gain insights into the responsibilities, challenges, and best practices associated with test management in SAP projects. Additionally, the webinar delves into the significance of heatmaps as a visual aid for identifying testing priorities, areas of risk, and resource allocation within SAP landscapes. Through this session, attendees can expect to enhance their understanding of test management principles while learning practical approaches to optimize testing processes in SAP environments using heatmap visualization techniques
What will you get from this session?
1. Insights into SAP testing best practices
2. Heatmap utilization for testing
3. Optimization of testing processes
4. Demo
Topics covered:
Execution from the test manager
Orchestrator execution result
Defect reporting
SAP heatmap example with demo
Speaker:
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
The Art of the Pitch: WordPress Relationships and SalesLaura Byrne
Clients don’t know what they don’t know. What web solutions are right for them? How does WordPress come into the picture? How do you make sure you understand scope and timeline? What do you do if sometime changes?
All these questions and more will be explored as we talk about matching clients’ needs with what your agency offers without pulling teeth or pulling your hair out. Practical tips, and strategies for successful relationship building that leads to closing the deal.
Alt. GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using ...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Essentials of Automations: The Art of Triggers and Actions in FMESafe Software
In this second installment of our Essentials of Automations webinar series, we’ll explore the landscape of triggers and actions, guiding you through the nuances of authoring and adapting workspaces for seamless automations. Gain an understanding of the full spectrum of triggers and actions available in FME, empowering you to enhance your workspaces for efficient automation.
We’ll kick things off by showcasing the most commonly used event-based triggers, introducing you to various automation workflows like manual triggers, schedules, directory watchers, and more. Plus, see how these elements play out in real scenarios.
Whether you’re tweaking your current setup or building from the ground up, this session will arm you with the tools and insights needed to transform your FME usage into a powerhouse of productivity. Join us to discover effective strategies that simplify complex processes, enhancing your productivity and transforming your data management practices with FME. Let’s turn complexity into clarity and make your workspaces work wonders!
DevOps and Testing slides at DASA ConnectKari Kakkonen
My and Rik Marselis slides at 30.5.2024 DASA Connect conference. We discuss about what is testing, then what is agile testing and finally what is Testing in DevOps. Finally we had lovely workshop with the participants trying to find out different ways to think about quality and testing in different parts of the DevOps infinity loop.
Unlocking Productivity: Leveraging the Potential of Copilot in Microsoft 365, a presentation by Christoforos Vlachos, Senior Solutions Manager – Modern Workplace, Uni Systems
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...James Anderson
Effective Application Security in Software Delivery lifecycle using Deployment Firewall and DBOM
The modern software delivery process (or the CI/CD process) includes many tools, distributed teams, open-source code, and cloud platforms. Constant focus on speed to release software to market, along with the traditional slow and manual security checks has caused gaps in continuous security as an important piece in the software supply chain. Today organizations feel more susceptible to external and internal cyber threats due to the vast attack surface in their applications supply chain and the lack of end-to-end governance and risk management.
The software team must secure its software delivery process to avoid vulnerability and security breaches. This needs to be achieved with existing tool chains and without extensive rework of the delivery processes. This talk will present strategies and techniques for providing visibility into the true risk of the existing vulnerabilities, preventing the introduction of security issues in the software, resolving vulnerabilities in production environments quickly, and capturing the deployment bill of materials (DBOM).
Speakers:
Bob Boule
Robert Boule is a technology enthusiast with PASSION for technology and making things work along with a knack for helping others understand how things work. He comes with around 20 years of solution engineering experience in application security, software continuous delivery, and SaaS platforms. He is known for his dynamic presentations in CI/CD and application security integrated in software delivery lifecycle.
Gopinath Rebala
Gopinath Rebala is the CTO of OpsMx, where he has overall responsibility for the machine learning and data processing architectures for Secure Software Delivery. Gopi also has a strong connection with our customers, leading design and architecture for strategic implementations. Gopi is a frequent speaker and well-known leader in continuous delivery and integrating security into software delivery.
Observability Concepts EVERY Developer Should Know -- DeveloperWeek Europe.pdfPaige Cruz
Monitoring and observability aren’t traditionally found in software curriculums and many of us cobble this knowledge together from whatever vendor or ecosystem we were first introduced to and whatever is a part of your current company’s observability stack.
While the dev and ops silo continues to crumble….many organizations still relegate monitoring & observability as the purview of ops, infra and SRE teams. This is a mistake - achieving a highly observable system requires collaboration up and down the stack.
I, a former op, would like to extend an invitation to all application developers to join the observability party will share these foundational concepts to build on:
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Albert Hoitingh
In this session I delve into the encryption technology used in Microsoft 365 and Microsoft Purview. Including the concepts of Customer Key and Double Key Encryption.
Generative AI Deep Dive: Advancing from Proof of Concept to ProductionAggregage
Join Maher Hanafi, VP of Engineering at Betterworks, in this new session where he'll share a practical framework to transform Gen AI prototypes into impactful products! He'll delve into the complexities of data collection and management, model selection and optimization, and ensuring security, scalability, and responsible use.
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf91mobiles
91mobiles recently conducted a Smart TV Buyer Insights Survey in which we asked over 3,000 respondents about the TV they own, aspects they look at on a new TV, and their TV buying preferences.
GraphRAG is All You need? LLM & Knowledge GraphGuy Korland
Guy Korland, CEO and Co-founder of FalkorDB, will review two articles on the integration of language models with knowledge graphs.
1. Unifying Large Language Models and Knowledge Graphs: A Roadmap.
https://arxiv.org/abs/2306.08302
2. Microsoft Research's GraphRAG paper and a review paper on various uses of knowledge graphs:
https://www.microsoft.com/en-us/research/blog/graphrag-unlocking-llm-discovery-on-narrative-private-data/
SAP Sapphire 2024 - ASUG301 building better apps with SAP Fiori.pdfPeter Spielvogel
Building better applications for business users with SAP Fiori.
• What is SAP Fiori and why it matters to you
• How a better user experience drives measurable business benefits
• How to get started with SAP Fiori today
• How SAP Fiori elements accelerates application development
• How SAP Build Code includes SAP Fiori tools and other generative artificial intelligence capabilities
• How SAP Fiori paves the way for using AI in SAP apps
Removing Uninteresting Bytes in Software FuzzingAftab Hussain
Imagine a world where software fuzzing, the process of mutating bytes in test seeds to uncover hidden and erroneous program behaviors, becomes faster and more effective. A lot depends on the initial seeds, which can significantly dictate the trajectory of a fuzzing campaign, particularly in terms of how long it takes to uncover interesting behaviour in your code. We introduce DIAR, a technique designed to speedup fuzzing campaigns by pinpointing and eliminating those uninteresting bytes in the seeds. Picture this: instead of wasting valuable resources on meaningless mutations in large, bloated seeds, DIAR removes the unnecessary bytes, streamlining the entire process.
In this work, we equipped AFL, a popular fuzzer, with DIAR and examined two critical Linux libraries -- Libxml's xmllint, a tool for parsing xml documents, and Binutil's readelf, an essential debugging and security analysis command-line tool used to display detailed information about ELF (Executable and Linkable Format). Our preliminary results show that AFL+DIAR does not only discover new paths more quickly but also achieves higher coverage overall. This work thus showcases how starting with lean and optimized seeds can lead to faster, more comprehensive fuzzing campaigns -- and DIAR helps you find such seeds.
- These are slides of the talk given at IEEE International Conference on Software Testing Verification and Validation Workshop, ICSTW 2022.
Climate Impact of Software Testing at Nordic Testing DaysKari Kakkonen
My slides at Nordic Testing Days 6.6.2024
Climate impact / sustainability of software testing discussed on the talk. ICT and testing must carry their part of global responsibility to help with the climat warming. We can minimize the carbon footprint but we can also have a carbon handprint, a positive impact on the climate. Quality characteristics can be added with sustainability, and then measured continuously. Test environments can be used less, and in smaller scale and on demand. Test techniques can be used in optimizing or minimizing number of tests. Test automation can be used to speed up testing.
UiPath Test Automation using UiPath Test Suite series, part 5DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 5. In this session, we will cover CI/CD with devops.
Topics covered:
CI/CD with in UiPath
End-to-end overview of CI/CD pipeline with Azure devops
Speaker:
Lyndsey Byblow, Test Suite Sales Engineer @ UiPath, Inc.
Dr. Sean Tan, Head of Data Science, Changi Airport Group
Discover how Changi Airport Group (CAG) leverages graph technologies and generative AI to revolutionize their search capabilities. This session delves into the unique search needs of CAG’s diverse passengers and customers, showcasing how graph data structures enhance the accuracy and relevance of AI-generated search results, mitigating the risk of “hallucinations” and improving the overall customer journey.
1. ALL* ABOUT SCALA
*ALL I COULD FIT IN 90 MINUTES PRESENTATION,
IN FACT THERE IS MUCH MORE TO SCALA…
Yardena Meymann
January 10, 2012
http://www.meetup.com/ILTechTalks/
1 of 99 Created on 10/01/2012
2. NAVIGATION
– Background
– Scala basics
– OOP in Scala
– FP in Scala
– Concurrency
– Tools
– Resources
2 of 99 Created on 10/01/2012
3. IT DOES NOT HAVE TO BE JAVA
it is tastier when you
Scala Java
Groovy
mix them!
Groovy Java
Scala Compiler
Compiler Compiler
Bytecode Bytecode Bytecode
Java Virtual Machine
3 of 99 Created on 10/01/2012
4. WHAT IS SCALA
– Object oriented and functional
– Statically typed - advanced type system
– Compiled to JVM bytecode
but also to CLR, and to JavaScript (in progress);
works with Dalvik
– High performance
– Very good interoperability with Java
– Support for modularity and extensibility
DSL friendly
4 of 99 Created on 10/01/2012
5. JAVA AND SCALA TIMELINE
lawsuit
2001
Java 7
(Dolphin)
2009 2011
€2.3 million
2011 2011
2.7 2008 2.8 2010
2.3 2007 2.9 2011
5 of 99 Created on 10/01/2012
6. THEN AND NOW
“If I were to pick a
language to use
today other than
Java, it would be
Scala”
James Gosling
6 of 99 Created on 10/01/2012
7. TOOLS
– IDE:
• built-in REPL, Scala IDE (based on Eclipse), IntelliJ and NetBeans plug-ins, ENSIME
scala>
– Tools
• https://wiki.scala-lang.org/display/SW/Tools+and+Libraries
• integration modules for almost every popular Java framework
7 of 99 Created on 10/01/2012
16. HELLO SCALA
package com.hp.scala
object HelloScala {
def main(args: Array[String]) {
println(“Hello Scala”)
}
}
package com.hp.scala;
public class object HelloScala {
public static void def main(String[] args: Array[String]) {
System.out.println(“Hello Scala”);
}
}
16 of 99 Created on 10/01/2012
17. HELLO SCALA - VARIABLES
object HelloScala {
def main(args: Array[String]) {
val msg = “Hello Scala”
println(msg)
}
}
17 of 99 Created on 10/01/2012
18. HELLO SCALA – TYPE INFERENCE
object HelloScala {
def main(args: Array[String]) {
val msg = “Hello Scala”
println(msg)
}
}
18 of 99 Created on 10/01/2012
19. VAL VS. VAR
object HelloScala {
def main(args: Array[String]) {
val msg = “Hello Scala”
println(msg)
msg = “Goodbye Java”
println(msg)
}
}
19 of 99 Created on 10/01/2012
20. VAL VS. VAR
object HelloScala {
def main(args: Array[String]) {
var msg = “Hello Scala”
println(msg)
msg = “Goodbye Java”
println(msg)
}
}
20 of 99 Created on 10/01/2012
21. METHODS (VERBOSE)
object HelloScala {
def main(args: Array[String]) {
println(hello(“Scala”))
}
def hello(who: String): String = {
return “Hello ” + who
}
}
21 of 99 Created on 10/01/2012
22. METHODS (SHORTER)
object HelloScala {
def main(args: Array[String]) {
println(hello(“Scala”))
}
def hello(who: String): String = {
“Hello ” + who
}
}
22 of 99 Created on 10/01/2012
23. METHODS (SHORTER YET)
object HelloScala {
def main(args: Array[String]) {
println(hello(“Scala”))
}
def hello(who: String) = {
“Hello ” + who
}
}
23 of 99 Created on 10/01/2012
24. METHODS (SHORT)
object HelloScala {
def main(args: Array[String]) {
println(hello(“Scala”))
}
def hello(who: String) = “Hello ” + who
}
24 of 99 Created on 10/01/2012
25. ARRAY ACCESS
object HelloScala {
def main(args: Array[String]) {
println(hello(args(0))
//args(0) is a shortcut for args.apply(0)
}
def hello(who: String) = “Hello ” + who
}
25 of 99 Created on 10/01/2012
26. CONDITION
object HelloScala {
def main(args: Array[String]) {
if (!args.isEmpty) println(hello(args(0))
}
def hello(who: String) = “Hello ” + who
}
//isEmpty() method has no arguments, and therefore can be
invoked without the ()
26 of 99 Created on 10/01/2012
27. IF EXPRESSION, NOT STATEMENT
object HelloScala {
def main(args: Array[String]) {
println(hello(
if (args.isEmpty) “Anonymous” else args(0)))
}
def hello(who: String) = “Hello ” + who
}
27 of 99 Created on 10/01/2012
28. FUNCTION OBJECT
object HelloScala {
def main(args: Array[String]) { …
}
val hello = (who: String) => “Hello “ + who
// equivalent to
//val hello = new Function1[String, String] {
// def apply(who: String): String = “Hello “ + who
//}
}
28 of 99 Created on 10/01/2012
29. FOREACH
object HelloScala {
def main(args: Array[String]) {
args.foreach(arg => println(hello(arg)))
}
def hello…
}
//example of anonymous function object
29 of 99 Created on 10/01/2012
30. OPERATORS, INFIX SYNTAX
def hello(who: String) = “Hello ”.+(who)
//same as “Hello ” + who
//NOTE that this is an example, not a recommended coding style:
def main(args: Array[String]) {
Console println hello (if (args isEmpty) “Anonymous” else args apply 0)
}
30 of 99 Created on 10/01/2012
31. MATCH EXPRESSIONS
– Matching on values (Java’s switch)
val times = 1
times match {
case 1 => "one"
case 2 => "two"
case _ => "some other number"
}
– No fall-through!
– Matching with guards
n match {
case it if 0 until 5 contains it => "less than five"
case it if 5 until 10 contains it => "less than ten"
case _ => "a lot“
}
31 of 99 Created on 10/01/2012
32. EXCEPTIONS
– Throwing an exception looks the same as in Java
– You catch exceptions using the syntax:
– NOTE: All exceptions in Scala are runtime
32 of 99 Created on 10/01/2012
33. CREATING A SEQUENCE
–Array(1,2,3)
• Arrays are mutable
–List(3.14, 2.72, 1.62)
• Lists are by default immutable, singly-linked
• Nil is an empty list
–Map: val romanNumeral =
Map(1 ->"I", 2 -> "II", 3 -> "III", 4 -> "IV", 5 -> "V“ )
// x -> y creates a tuple (x,y)
33 of 99 Created on 10/01/2012
34. MAP VALUES – ANOTHER OPTION
–What if key is not in the Map?
–Map.get returns an Option:
• Some(value), value can be retrieved with get
• or None
–getOrElse method allows to specify default:
• treasureMap.getOrElse(1, “Oops”)
• treasureMap.getOrElse(4, “Oops”)
–Safe alternative to null-checks
34 of 99 Created on 10/01/2012
Scala
35. OPERATING WITH A SEQUENCE
– foreach(E=>Unit), – exists(E=>Boolean),
– filter(E=>Boolean), – remove(E=>Boolean),
– map(E=>X), – reverse,
– reduceLeft((E,E)=>E), – sort((E,E)=>Boolean),
– take(Int), – head,
– drop(Int), – tail,
– indexOf(E), – … more later
35 of 99 Created on 10/01/2012
36. RICH WRAPPERS
– A Range can be created: „a‟ to „z‟ or 1 until 10
– Scala compiler made an implicit conversion of Int to
scala.runtime.RichInt
• To check if conversion is available: implicitly[Int => RichInt]
(in REPL first import scala.runtime._)
• Alternatively: scalac –Xprint:typer
– Another Example:
• reg-exp
• "()?(d+)(.d*)?".r
36 of 99 Created on 10/01/2012
37. PLACEHOLDER
(1 to 10) filter ((i: Int) => i%2 == 0) mkString “,”
or equivalent shorter version:
… filter (i => i%2 == 0)
or yet shorter using placeholder:
… filter (_ %2 == 0)
(1 to 10).reduceLeft((acc: Int, i: Int) => acc + i)
or equivalent shorter version:
… reduceLeft((acc, i) => acc + i)
or yet shorter using placeholders:
… reduceLeft(_ + _)
37 of 99 Created on 10/01/2012
38. CLOSURES
–So far, function literals have referred only to
passed parameters
(x: Int) => x > 0
–You can, however, refer to variables defined
elsewhere
(x: Int) => x + more // how much more?
–more is a free variable, because the function
literal does not itself give a meaning to it.
–x variable, by contrast, is a bound variable.
38 of 99 Created on 10/01/2012
39. CLOSURES
The function value (the object) that’s created at
runtime from addMore function literal is called a
closure.
The name arises from the act of “closing” the function literal by
“capturing” the bindings of its free variables
39 of 99 Created on 10/01/2012
40. EXAMPLE
def tryWithLogging (s: => Unit) {
try {
s
} catch {
case ex: Exception => ex.printStackTrace()
}
}
val file = new File(“test.txt”)
tryWithLogging {
val writer = new PrintWriter(file)
writer.println(“this is a test”)
}
If you’re passing exactly one argument to a method, you can use curly
braces instead of parentheses to surround it.
40 of 99 Created on 10/01/2012
41. HELLO SCALA – FOR COMPREHENSION
object HelloScala {
def main(args: Array[String]) {
for (arg ← args) println(hello(arg)))
}
def hello…
}
41 of 99 Created on 10/01/2012
42. MORE ON FOR EXPRESSION
–map alternative – yield:
def scalaFiles =
for {
file (new java.io.File(".")).listFiles
if file.getName.endsWith(".scala")
} yield file
• When the for expression completes, the result will include
all of the yielded values contained in a single collection.
• The type of the resulting collection is based on the kind of
collections processed in the iteration clauses.
42 of 99 Created on 10/01/2012
43. SCALA HIERARCHY
– Nothing is the subtype of all other types.
• It has no instances.
• It is used primarily for defining other types in a
type-safe way, such as the
special List subtype Nil.
– Null has one instance, null,
corresponding to the runtime’s concept
of null.
– FunctionN[-T1, -T2, …, -TN, +R] a
function that takes N arguments
– Product - arity and getting nth item in a
“cartesian product”.
• Subtraits are defined for Product,
called ProductN, for dimension N from 1 through
22.
– TupleN case classes for arity N = 1
through 22.
• Tuples support the literal syntax (x1, x2, …, xN)
43 of 99 Created on 10/01/2012
45. SIMPLE CLASS
–Like in Java classes are defined with class and
instances created with new
–Declaring properties is much simpler
Java Scala
public class Person { class Person (var name: String)
private String name = null;
public Person(String name) {
this.name = name;
} …
public String getName() { person = new Person(“Martin”)
return name; println(person.name)
}
public void setName(String name) {
this.name = name;
}
}
45 of 99 Created on 10/01/2012
46. SIMPLE CLASS
scala> class Lang {
| val name: String = “Scala"
| def add(m: Int, n: Int): Int = m + n
| }
defined class Lang
scala> val lang = new Lang
lang: Lang = Lang@e74a51
scala> lang.add(1, 2)
res1: Int = 3
scala> lang.name
res2: String = “Scala"
46 of 99 Created on 10/01/2012
48. EXTENDING CLASSES
class ArrayElement(conts: Array[String]) extends Element {
def contents: Array[String] = conts
}
class LineElement(s: String) extends ArrayElement(Array(s)) {
override def width = s.length
override def height = 1
}
48 of 99 Created on 10/01/2012
49. SINGLETON & COMPANION OBJECTS
– Scala is more object-oriented than Java is that classes in Scala
cannot have static members. Instead, Scala has singleton
objects.
– A singleton object definition looks like a class definition, except
instead of the keyword class you use the keyword object.
– When a singleton object shares the same name with a class, it
is called that class’s companion object.
object Rational {
…
}
– A singleton object that does not share the same name with a
companion class is called a standalone object.
49 of 99 Created on 10/01/2012
50. COMPANION OBJECT AS A FACTORY
– Companion objects are excellent fit for implementing
Factory design patterns
– Naming the method apply allows invocation like Array(“a”,
“b”, “c”) instead of Array.apply(“a”, “b”, “c”)
50 of 99 Created on 10/01/2012
51. BUILDER PATTERN IN SCALA
– From Josh Bloch’s “Effective Java” 2nd ed.:
public class NutritionFacts {
private final int servingSize; // (mL) required
private final int servings; // (per container) required
private final int calories; // optional
private final int fat; // (g) optional
private final int sodium; // (mg) optional
private final int carbohydrate;// (g) optional
… }
– In Scala:
class NutritionFacts(servingSize, servings, calories = 0, fat =
0, sodium = 0, carbohydrate = 0)
Creating an instance:
new NutritionFacts(servings = 3, servingSize = 200, fat = 1)
51 of 99 Created on 10/01/2012
52. CASE CLASSES – VALUE OBJECTS
case class Point(x: Double, y: Double)
abstract class Shape() { def draw(): Unit }
case class Circle(center: Point, radius: Double) extends Shape() {
def draw() { … }
}
case class Rectangle(x: Point, height: Double, width: Double) extends Shape() {
def draw() { … }
}
case class Triangle(point1: Point, point2: Point, point3: Point) extends Shape() {
def draw() { … }
}
– Using the case modifier makes the Scala compiler
add some syntactic conveniences to your class
•…
52 of 99 Created on 10/01/2012
53. CASE CLASS MAGIC
– Compiler automatically creates factory method:
val c = Circle(Point(2.0,1.0),3.0) instead of
val c = new Circle(new Point(2.0,1.0),3.0)
– All constructor arguments automatically become immutable fields
– Compiler automatically implements equals, hashCode, and toString
methods to the class, using the fields specified as constructor
arguments
case classes are always compared structurally
– Compiler adds a copy method for making modified copies
The method works by using named and default parameters. You specify the
changes you’d like to make by using named parameters. For any parameter
you don’t specify, the value from the old object is used.
val r = Rectangle(Point(1.0,2.0), 3.0, 4.0)
r.copy(height=5.0)
– We can pattern match on case classes…
53 of 99 Created on 10/01/2012
54. CASE CLASSES – PATTERN MATCHING
def matchOn(shape: Shape) = shape match {
case Circle(center, radius) =>
println("Circle: center = "+center+", radius = "+radius)
case Rectangle(x, h, w) =>
println("Rectangle: lower-left = "+x+", height = "+h+", width = "+w)
case Triangle(p1, p2, p3) =>
println("Triangle: point1 = "+p1+", point2 = "+p2+", point3 = "+p3)
case _ => println("Unknown shape!"+shape)
}
val shapesList = List(
Circle(Point(0.0, 0.0), 1.0), Circle(Point(5.0, 2.0), 3.0),
Rectangle(Point(0.0, 0.0), 2, 5), Rectangle(Point(-2.0, -1.0), 4, 3),
Triangle(Point(0.0, 0.0), Point(1.0, 0.0), Point(0.0, 1.0))
)
shapesList.foreach { shape => matchOn(shape) }
54 of 99 Created on 10/01/2012
56. TRAITS
– A trait definition looks just like a class definition except that it uses the
keyword trait
trait Philosophical {
def philosophize() { println("I consume memory, therefore I am!") }
}
– Once a trait is defined, it can be mixed in to a class using either the
extends or with keywords
class Frog extends Philosophical { … }
– Traits facilitate multiple inheritance: a class can mix in any number of
traits. “He who defs last defs best”.
class Animal { … }
trait HasLegs { val legsNumber : Int }
class Frog extends Animal with Philosophical with HasLegs {
override val legsNumber = 4
override def philosophize() { println(“It ain't easy being green”) }
}
56 of 99 Created on 10/01/2012
57. THE TRAITS OF TRAITS
– Traits can be also mixed in when creating individual
objects:
val frog = new Animal with Philosophical
– You can do anything in a trait definition that you can do in
a class definition, with only two exceptions:
• traitcannot have any “class” parameters, i.e., parameters passed to
the primary constructor of a class
trait NoPoint(x: Int, y: Int) // Does not compile
• in classes, super calls are statically bound, in traits, they are
dynamically bound (enables stackable modifications pattern)
– Trait, like any class can have a companion object
• selfless trait – trait Util { … }; object Util extends Util
57 of 99 Created on 10/01/2012
58. TRAITS – A PRACTICAL EXAMPLE
class Trade(refNo: String, account: String, instrument: String,
quantity: Int, unitPrice: Int) {
// principal value of the trade
def principal = quantity * unitPrice
}
trait Tax {
def calculateTax
}
trait Commission {
def calculateCommission
}
val trade = new Trade(..) with Tax with Commission {
// implementations
def calculateTax = principal * 0.2
def calculateCommission = principal * 0.15
}
58 of 99 Created on 10/01/2012
59. TRAITS – REQUIRE (SELF TYPE)
– Sometimes you want to constrain what the trait can be
mixed in with, for example:
// abstractions Tax and Commission should be constrained to be used
with the Trade abstraction only
trait Tax { self: Trade =>
def calculateTax = principal*0.2 //refers to principal of trade
}
trait Commission { self: Trade =>
def calculateCommission = principal*0.15 //refers to principal of trade
}
– When you say B extends A, then B is an A, while here you
define the relationship of B requires an A
59 of 99 Created on 10/01/2012
60. TRAITS – DI WITH THE CAKE PATTERN
– The pattern based on Scala traits was first introduced by Martin Odersky’s
paper “Scalable Component Abstractions”
– The pattern also uses nested classes: Scala, like Java, supports nesting of
classes in one another
– Demo
http://jonasboner.com/2008/10/06/real-world-scala-dependency-injection-di.html
60 of 99 Created on 10/01/2012
61. ANNOTATIONS – JPA EXAMPLE
@Entity
@NamedQuery{val name = "findAllBook", val query = "SELECT b FROM Book b"}
class Book extends Id with Description {
@Column{val nullable = false}
@BeanProperty var title: String
@BeanProperty var price: Float
@BeanProperty var isbn: String
@BeanProperty var nbOfPage: Int
@BeanProperty var illustrations: Boolean
}
trait Id {
@javax.persistence.Id
@GeneratedValue{val strategy = GenerationType.IDENTITY}
@BeanProperty var id: Long
}
trait Description {
@Column{val length = 2000}
@BeanProperty var description: String
}
61 of 99 Created on 10/01/2012
62. PACKAGES
– You can place code into named packages in Scala:
• Either place the contents of an entire file into a package by putting a package
clause at the top of the file (like in Java)
• Or follow a package clause by a section in curly braces that contains the
definitions that go into the package (like C# namespaces).
– Objects are a useful tool for organizing static functions.
62 of 99 Created on 10/01/2012
63. PACKAGE OBJECTS
– Scala version 2.8 introduces a new scoping construct
called package objects
• they are used to define types, variables, and methods that are visible
at the level of the corresponding package
• they can contain aliases to classes and objects
• they provide a clear separation between the abstractions exposed by
a package and the implementations that should be hidden inside it
package object scala {
type Iterable[+A] = scala.collection.Iterable[A]
val Iterable = scala.collection.Iterable
…
}
63 of 99 Created on 10/01/2012
64. IMPORT
– Use import in REPL and anywhere in your .scala file
• Single file: import package.Class
• All files: import package._
• Multiple files: import package.{A,B,C}
• Renaming: import package.{A=>B}
• Import all except: import package.{A=>_, _}
– Example:
import java.sql.{Date=>SDate,_}
– Imports are relative, but you can use _root_. … to import a FQN
– Import also works with Objects
– You can limit the scope of any declaration, including import, with
locally { … }
64 of 99 Created on 10/01/2012
66. OVERVIEW
– In mathematics, functions have no side effects
• No matter how much work sin(x) does, all the results are returned
and assigned to y. No global state of any kind is modified internally by
sin(x). Hence, we say that such a function is free of side-
effects or pure.
– This obliviousness to the surrounding context is known
as referential transparency.
• You can call such a function anywhere and be confident that it will
always behave the same way. If no global state is modified,
concurrent invocation of the function is straightforward and reliable.
66 of 99 Created on 10/01/2012
67. OVERVIEW
– In functional programming variables are immutable.
• In the expression y = sin(x), once you pick x, then y is fixed
• Functional programming languages prevent you from assigning a new value
to a variable that already has a value.
• Besides concurrency, immutability has other benefits…
– “Functional manifesto”
• valover var
• Composition over inheritance
• Immutable collections
• Recursion over imperative iteration
• Pattern matching over encapsulation
•…
67 of 99 Created on 10/01/2012
68. LAZY VAL
– If you prefix a val definition with a lazy modifier, the initializing
expression on the right-hand side will only be evaluated the first
time the val is used.
– unlike def, lazy val is never evaluated more than once.
• after the first evaluation of a lazy val the result of the evaluation is stored,
to be reused when the same val is used subsequently.
68 of 99 Created on 10/01/2012
69. CALL BY NAME PARAMETERS
–Typically, parameters to functions are by-
value parameters – the value of the parameter is
determined before it is passed to the function
–Sometimes we don’t want a parameter evaluated
until it’s accessed within our function
–A by-name parameter is specified by omitting the
parentheses that normally accompany a function
parameter
def myCall (parameter: => ReturnType)
69 of 99 Created on 10/01/2012
70. CALL BY NAME PARAMETERS USE-
CASE
– When logging, we create messages by concatenating Strings, even if we
don't use these messages in the end because the logging level is not
enabled.
– To fix the problem, we often insert manual checks in client code whether
the logging level is enabled, e.g. by calling
if (logger.isDebugEnabled()) logger.debug(…)
– SLF4S, Scala logging library, uses by-name parameters
def debug(msg: => String) {
require(msg != null, "msg must not be null!")
if (slf4jLogger.isDebugEnabled) slf4jLogger debug msg
}
– SLF4S also provides Logging trait that can be mixed in into any class
class MyClazz extends SomeClazz with Logging
...
logger debug "SLF4S just rocks!"
...
70 of 99 Created on 10/01/2012
71. CURRYING
– Currying – a way to write functions with multiple
parameter lists.
• For instance def f(x: Int)(y: Int) is a curried function with two
parameter lists.
• A curried function is applied by passing several arguments lists, as in:
f(3)(4).
– Examples:
def plainOldSum(x: Int, y: Int) = x + y
plainOldSum(1, 2)
def curriedSum(x: Int)(y: Int) = x + y
curriedSum(1)(2)
val onePlus: (Int) => Int = curriedSum(1)_
onePlus(2) //3
71 of 99 Created on 10/01/2012
72. CURRYING EXAMPLE
– foldLeft/Right
– withResource (the loan pattern)
def using[R <: Closeable] (resource: R)(block: R => Unit) {
try {
block(resource)
} finally {
if (resource != null) resource.close()
}
}
• Usage Example:
using(new BufferedReader(new FileReader("file"))) { r =>
… r.readLine …
}
72 of 99 Created on 10/01/2012
73. PARTIALLY-APPLIED FUNCTIONS
– A partially applied function is an expression in which you
don’t supply all of the arguments needed by the function.
Instead, you supply some, or none, of the needed
arguments.
scala> def sum(a: Int, b: Int, c: Int) = a + b + c
sum: (a: Int,b: Int,c: Int)Int
scala> val a = sum _
a: (Int, Int, Int) => Int = <function3>
a(1, 2, 3) //6
supplying some arguments: val b = sum(1, _: Int, 3)
b: (Int) => Int = <function1>
scala> b(2) //6
73 of 99 Created on 10/01/2012
75. MOTIVATION
Moor’s Law
• “The number of
transistors on a chip will
double approximately
every 18 months”
Gordon E. Moore, 1965
Free Lunch
Free and regular performance gains, even without releasing new
versions or doing anything special
75 of 99 Created on 10/01/2012
76. FREE LUNCH IS OVER
– Hardware crossed a boundary in the early 2000s:
• chips got big enough, cycle speed got fast enough
• a signal can no longer reach the whole chip in a clock cycle
• problems with heat dissipation
– Processor manufacturers have turned towards multi-core
processors Capable of doing multiple calculations in
parallel
• CPU speeds are likely to stay relatively flat in the near future
• The speedup of a program using multiple processors in parallel
computing is limited by the sequential fraction of the program.
76 of 99 Created on 10/01/2012
77. SHARED STATE CONCURRENCY
–Shared mutable state is problematic
–We need locking mechanism
–Thread concurrently executes code sections
• Contains resources that must be shared
• Synchronized in order to guarantee
−Correct ordering
−Visibility
−Data consistency
77 of 99 Created on 10/01/2012
78. PROBLEMS WITH LOCKING
–Hard to program correctly
• Race conditions
• Also hard to test and debug
–Synchronizing too much
• Deadlocks
• Makes your program serial
78 of 99 Created on 10/01/2012
80. ACTORS
–Message-passing instead of shared state
–Originated:
• CarlHewitt (early 70s)
• Gul Agha (80s)
–Popularized by Erlang implementation
• A pure functional, dynamically typed language invented in
1986 at Ericsson
–Actors are related to original OO ideas
• Actors encapsulate state and behavior (like objects)
• Actors are logically active (unlike most objects)
80 of 99 Created on 10/01/2012
81. ACTORS
– No shared state between actors
– Asynchronous message-passing
– Mailbox to buffer incoming
messages
– React to received messages by
executing a behavior function
• can only change the state of the actor itself
• can send messages to other actors
– Actors never share state and thus
never need to compete for locks for
access to shared data
81 of 99 Created on 10/01/2012
82. AKKA
– Akka is the platform for next generation event-driven, scalable, and
fault-tolerant architectures on the JVM
– Written in Scala, can be used with Scala or Java
– Each actor instance runs in only one thread at a time, so no
synchronization is required for actor state.
– Akka dispatcher schedules actors on threads – or even on multiple
machines – as needed. Can have millions of actors, an actor does not
“use up” a thread.
82 of 99 Created on 10/01/2012
83. SIMPLE AKKA ACTOR
case object Tick
class Counter extends Actor {
private var counter = 0
def receive = {
case Tick =>
counter += 1
println(counter)
}
}
val counter = actorOf[Counter]
counter.start
83 of 99 Created on 10/01/2012
84. SEND
–Fire and forget
counter ! Tick
–Uses Future under the hood (with time-out)
val result = (actor !! Message).as[String]
–Returns the Future directly
val future = actor !!! Message
future.await
val result = future.get
...
Futures.awaitOne(List(fut1, fut2, ...))
Futures.awaitAll(List(fut1, fut2, ...))
84 of 99 Created on 10/01/2012
85. REPLY
class SomeActor extends Actor {
def receive = {
case User(name) =>
// use reply
self.reply(“Hi ” + name)
}
}
store away the sender to use later or somewhere else
... = self.sender
85 of 99 Created on 10/01/2012
86. SCALA AND AKKA
– Immutable messages : case classes, tuples, lists
– Dispatchers
– Let it fail – Supervisor Hierarchies
• One for One
• All for One
• Supervise the supervisor
– Remote actors
– Transactors: STM using Actors
86 of 99 Created on 10/01/2012
88. SBT – SIMPLE BUILD TOOL
– Build your projects using Scala
– Create an sbt shell script: java -Xmx512M -jar sbt-launch.jar "$@“
– Launch it: sbt
– Interactive mode: e.g. compile
– Make an action run when a source file changes prefixing the action with ~.
– project/build/SbtDemoProject.scala
import sbt._
class SbtDemoProject(info: ProjectInfo) extends DefaultProject(info) {
val specs = "org.scala-tools.testing" % "specs_2.8.0" % "1.6.5" % "test"
lazy val hi = task { println("Hello World"); None }
override def compileOptions = super.compileOptions ++ Seq(Unchecked)
}
<dependency>
<groupId>org.scala-tools.testing</groupId>
– In sbt console: reload <artifactId>specs_2.8.0</artifactId>
<version>1.6.5</version>
<scope>test</scope>
– In sbt console: hi </dependency>
88 of 99 Created on 10/01/2012
89. PLAY! FRAMEWORK
– Both Scala and Java friendly
– Stateless
• Play is “share-nothing” so no need for communication between nodes
• State can be kept in your SQL or NoSQL store, in memcached, or browser cookies
– Emphasis on rapid development and good defaults, rather than
absolute flexibility
• No compile and restart; server compiles and recompiles on the fly, so just edit, reload,
edit, reload. Compilation and other errors appear right in the browser.
– Try out the Java or Scala tutorials on the Play website
play new helloworld --with scala
play run
89 of 99 Created on 10/01/2012
90. UNIT TESTING
–To test in Scala you can use Java tools:
• JUnit
• TestNG
–Or frameworks built especially for Scala:
• ScalaTest
• Specs
• ScalaCheck
90 of 99 Created on 10/01/2012
Scala
92. UNIT TESTING – SCALATEST + JUNIT
– If you wish to use ScalaTest’s assertion syntax in your JUnit 3 test, however, you
can instead subclass JUnit3Suite
– ScalaTest also has a JUnitWrapperSuite, which enables you to run existing JUnit
tests written in Java with ScalaTest’s runner.
92 of 99 Created on 10/01/2012
94. TEST AS SPECIFICATION
– In a FlatSpec, you write tests as specifier clauses.
• You start by writing a name for the subject under test as a string,
• then should (or must or can),
• then a string that specifies a bit of behavior required of the subject,
• then in.
• In the curly braces following in, you write code that tests the specified behavior.
• In subsequent clauses you can write it to refer to the most recently given subject.
– When a FlatSpec is executed, it will run each specifier clause as a ScalaTest
test.
• FlatSpec (and ScalaTest’s other specification traits) generate output that reads more like a
specification when run.
94 of 99 Created on 10/01/2012
Scala
95. TEST AS SPECIFICATION - SPECS
– specs is another open source testing framework inspired
by Ruby’s RSpec
95 of 99 Created on 10/01/2012
96. PROPERTY-BASED TESTING
– ScalaCheck enables you to specify properties that the code under test
must obey.
– For each property, ScalaCheck will generate test data and run tests
that check whether the property holds.
96 of 99 Created on 10/01/2012
98. MORE ON SCALA
– http://www.scala-lang.org
– http://typesafe.com/
– Scala School http://twitter.github.com/scala_school/
– Programming In Scala http://www.artima.com/pins1ed/
– Programming Scala http://ofps.oreilly.com/titles/9780596155957/
– Scala Style Guide http://davetron5000.github.com/scala-style/
– StackOverflow http://stackoverflow.com/questions/tagged/scala
98 of 99 Created on 10/01/2012
99. THANK YOU
If you are interested in programming languages,
join http://www.lambda.org.il
99 of 99 Created on 10/01/2012
Editor's Notes
The major deviation from Java concerns the syntax for type annotations—it’s“variable: Type” instead of “Type variable” in Java. Scala’s postfix type syntax resemblesPascal, Modula-2, or Eiffel. The main reason for this deviation has to do with typeinference, which often lets you omit the type of a variable or the return type of a method.Using the “variable: Type” syntax this is easy—just leave out the colon and the type. Butin C-style “Type variable” syntax you cannot simply leave off the type—there would be nomarker to start the definition anymore. You’d need some alternative keyword to be a placeholderfor a missing type (C# 3.0, which does some type inference, uses var for this purpose).Such an alternative keyword feels more ad-hoc and less regular than Scala’s approach.
That plus sign between the strings? It’s a method. First, Scala allows non-alphanumeric method names. You can call methods +, -, $, or whatever you desire. Second, this expression is identical to 1 .+(2). (We put a space after the 1 because 1. would be interpreted as aDouble.) When a method takes one argument, Scala lets you drop both the period and the parentheses, so the method invocation looks like an operator invocation. This is called “infix” notation, where the operator is between the instance and the argument. We’ll find out more about this shortly.To facilitate a variety of readable programming styles, Scala is flexible about the use of parentheses in methods. If a method takes no parameters, you can define it without parentheses. Callers must invoke the method without parentheses. If you add empty parentheses, then callers may optionally add parentheses. For example, the size method for List has no parentheses, so you write List(1, 2, 3).size. If you try List(1, 2, 3).size(), you’ll get an error. However, the length method for String does have parentheses in its definition, so both"hello".length() and "hello".length will compile.The convention in the Scala community is to omit parentheses when calling a method that has no side-effects. So, asking for the size of a sequence is fine without parentheses, but defining a method that transforms the elements in the sequence should be written with parentheses.It’s also possible to omit the dot (period) when calling a parameterless method or one that takes only one argument
Because map takes one argument, a function, we can use the “placeholder” indicator _ instead of a named parameter. That is, the _ acts like an anonymous variable, to which each string will be assigned before toUpperCase is called. Note that the String type is inferred for us, too. As we will see, Scala uses _ as a “wild card” in several contexts.