This is brief presentation on the Scala programming language. It is aimed at Java developers who are curious about Scala. It was given at a San Francisco Java User Group in January 2009.
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/
"The joy of Scala" - Maxim Novak / Wix
Around eight years ago I started my journey as a developer. Since then, I've played around with many languages and thought that C# offers the best developer productivity. After joining Wix two years ago, I was exposed to the amazing world of Scala and Functional Programming and never looked back.
In Scala the code is much more concise, less ceremonious, immutable by default, combines functional with object oriented, seamlessly interoperates with Java, and many software engineering patterns are already baked into the language. Most importantly - Scala is FUN! By the end of the session you too will, hopefully, convert to Scala and never look back.
Recording of the lecture (Hebrew) - https://youtu.be/TcnYTwff2xU
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
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/
"The joy of Scala" - Maxim Novak / Wix
Around eight years ago I started my journey as a developer. Since then, I've played around with many languages and thought that C# offers the best developer productivity. After joining Wix two years ago, I was exposed to the amazing world of Scala and Functional Programming and never looked back.
In Scala the code is much more concise, less ceremonious, immutable by default, combines functional with object oriented, seamlessly interoperates with Java, and many software engineering patterns are already baked into the language. Most importantly - Scala is FUN! By the end of the session you too will, hopefully, convert to Scala and never look back.
Recording of the lecture (Hebrew) - https://youtu.be/TcnYTwff2xU
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 is a programming language that mixes object oriented and functional programming in a powerful and flexible way. While it can not be considered as a mainstream language, it has seen a growing adoption trend.An important ingredient for this diffusion is its complete interoperability with Java and the fact that it runs on a solid platform such as the JVM.
It is currently the 4th most loved programming language and the 2nd top paying technology of 2016 (StackOverflow Developers Survey).
These slides have been used for a 4h seminar at the University of Cagliari the 17th of December 2016
Watch video (in Hebrew): http://parleys.com/play/53f7a9cce4b06208c7b7ca1e
Type classes are a fundamental feature of Scala, which allows you to layer new functionality on top of existing types externally, i.e. without modifying or recompiling existing code. When combined with implicits, this is a truly remarkable tool that enables many of the advanced features offered by the Scala library ecosystem. In this talk we'll go back to basics: how type classes are defined and encoded, and cover several prominent use cases.
A talk given at the Underscore meetup on 19 August, 2014.
Slides for my recent presentation at the CASE meetup, May 21st. Discusses functional programming features in Scala. Goes from basic FP features like higher-order functions all the way through to monads.
In functional programming, words from Category Theory are thrown around, but how useful are they really?
This session looks at applications of monoids specifically and how using their algebraic properties offers a solid foundation of reasoning in many types of business domains and reduces developer error as computational context complexity increases.
This will provide a tiny peak at Category Theory's practical uses in software development and modeling. Code examples will be in Haskell and Scala, but monoids could be constructed in almost any language by software craftsmen and women utilizing higher orders of reasoning to their code.
Le slide deck de l'Université que nous avons donnée avec Rémi Forax à Devoxx France 2019.
Comme promis, Java sort sa version majeure tous les 6 mois. Le train passe et amène son lot de nouveautés. Parmi elles, certaines sont sorties : une nouvelle syntaxe pour les clauses switch et l'instruction de byte code CONSTANT_DYNAMIC. D'autres sont en chantier, plus ou moins avancé : une nouvelle façon d'écrire des méthodes de façon condensée, un instanceof 'intelligent', des constantes évaluées au moment où elles sont utilisées. Les projets progressent. Loom, et son nouveau modèle de programmation concurrente que l'ont peut tester avec Jetty. Amber, qui introduit les data types et des nouvelles syntaxes. Valhalla, dont les value types donnent leurs premiers résultats. S'il est difficile de prévoir une date de sortie pour ces nouveautés, on sait en revanche qu'une fois prêtes elles sortiront en moins de 6 mois. De tout ceci nous parlerons donc au futur et en public, avec des démonstrations de code, des slides, du code, de la joie et de la bonne humeur !
Scala is a programming language that mixes object oriented and functional programming in a powerful and flexible way. While it can not be considered as a mainstream language, it has seen a growing adoption trend.An important ingredient for this diffusion is its complete interoperability with Java and the fact that it runs on a solid platform such as the JVM.
It is currently the 4th most loved programming language and the 2nd top paying technology of 2016 (StackOverflow Developers Survey).
These slides have been used for a 4h seminar at the University of Cagliari the 17th of December 2016
Watch video (in Hebrew): http://parleys.com/play/53f7a9cce4b06208c7b7ca1e
Type classes are a fundamental feature of Scala, which allows you to layer new functionality on top of existing types externally, i.e. without modifying or recompiling existing code. When combined with implicits, this is a truly remarkable tool that enables many of the advanced features offered by the Scala library ecosystem. In this talk we'll go back to basics: how type classes are defined and encoded, and cover several prominent use cases.
A talk given at the Underscore meetup on 19 August, 2014.
Slides for my recent presentation at the CASE meetup, May 21st. Discusses functional programming features in Scala. Goes from basic FP features like higher-order functions all the way through to monads.
In functional programming, words from Category Theory are thrown around, but how useful are they really?
This session looks at applications of monoids specifically and how using their algebraic properties offers a solid foundation of reasoning in many types of business domains and reduces developer error as computational context complexity increases.
This will provide a tiny peak at Category Theory's practical uses in software development and modeling. Code examples will be in Haskell and Scala, but monoids could be constructed in almost any language by software craftsmen and women utilizing higher orders of reasoning to their code.
Le slide deck de l'Université que nous avons donnée avec Rémi Forax à Devoxx France 2019.
Comme promis, Java sort sa version majeure tous les 6 mois. Le train passe et amène son lot de nouveautés. Parmi elles, certaines sont sorties : une nouvelle syntaxe pour les clauses switch et l'instruction de byte code CONSTANT_DYNAMIC. D'autres sont en chantier, plus ou moins avancé : une nouvelle façon d'écrire des méthodes de façon condensée, un instanceof 'intelligent', des constantes évaluées au moment où elles sont utilisées. Les projets progressent. Loom, et son nouveau modèle de programmation concurrente que l'ont peut tester avec Jetty. Amber, qui introduit les data types et des nouvelles syntaxes. Valhalla, dont les value types donnent leurs premiers résultats. S'il est difficile de prévoir une date de sortie pour ces nouveautés, on sait en revanche qu'une fois prêtes elles sortiront en moins de 6 mois. De tout ceci nous parlerons donc au futur et en public, avec des démonstrations de code, des slides, du code, de la joie et de la bonne humeur !
An Introduction to core ideas, characteristics and benefits of functional programming and their implementation within the so called ‘object – functional’ language Scala.
Leaving the widely known concepts of object oriented programming aside, the focus is directed on how to leverage Scala in order to perform the following topics (extract):
* Functions and Function types
* Lambdas and Closures
* Currying and partial Argument Application
* Algebraic datatypes and Pattern matching
* Higher Order Functions
* Composition and Combinators
What's new with Scala 2.10.0? A brief look at the past, and a detailed look at what's coming down the pipeline.
Note: at the time this presentation was created, Scala 2.10.0 had not been released yet. The final version will probably differ in some ways.
Last update: September 20th
Scala for Java Developers (Silicon Valley Code Camp 13)Ramnivas Laddad
My presentation at Silicon Valley Code Camp 13 (http://www.siliconvalley-codecamp.com/Session/2013/scala-for-java-developers). The target audience is Java developers who wants to get started with Scala.
This presentation is based on Joakim\’s experiences from moving from Java to Scala http://www.scala-lang.org/node/960#Joak We will explore how to move from Java to Scala and why. We\’ll look at things that you will run into sooner rather than later such as Scala\’s collection APIs, Options and higher order functions and special syntax. You will leave this presentation with good foundation to use Scala in practice; perhaps even in your current Java project and ideally with an appetite to learn more.
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.
Functional Database Strategies at Scala BayJason Swartz
As developers using a functional programming language, we embrace immutable collections and pure functions in our code. However, we often have separate rules for how we work with our persistent collections in databases. In this talk we'll look at why & how to take a more functional approach to persistence with databases, from managing the connections, using immutable table rows, and considering event-source persistence
City Tracks add a metaphor to exercise, an extra motivation, a rewarding stimulus so that walking and jogging be more than just that.
Run in the Formula 1 circuits, jog in the most appealing cities in the world, walk for a cause. This Rexona app will lead you to DO:MORE.
Ajax, JSON & jQuery
"JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.”
– json.org
JSON is often used in Ajax calls instead of XML because it’s more lightweight compared to XML, less text is needed for defining the same data.
This is a talk about some of the higher level topics that you need to think when design an Android app. These include architecture, security, hybrid apps, SDKs, logging, and testing.
Design Patterns for Tablets and SmartphonesMichael Galpin
This is a talk I gave at AnDevCon. It talks about ways to take advantage of features introduced in Android 3.0 to create more modular and better looking apps.
That’s My App - Running in Your Background - Draining Your BatteryMichael Galpin
You have seen the ads where Android based devices like to brag about how awesome their multitasking is and now even the iPhone claims to have multitasking. Unfortunately it’s pseudo-multitasking borrowed from Android, but fear not. Android has “real” multitasking as well. It’s easy to do, but even easier to screw up. In this talk you’ll learn how to do it right, and how to do it without killing a phone’s battery. We’ll discuss the dreaded “P” word (polling), as well as alternatives such as Android’s cloud to device messaging and persistent connections.
Are the smartphone wars wearing your out? When asked to choose between Objective-C and Java do you answer “None of the Above”? Do you think app stores are so 1995? Then there is good news for you and it’s called the mobile web. This isn’t about trying to port iFart to the browser, and it’s definitely not about tweaking an existing website so it doesn’t look awful on your mom’s iPhone. It is about writing full featured, engaging applications on the web. This talk is all about how to create killer web apps using HTML5, CSS3, as well as some other not-so-standard technologies available on a wide variety of popular smartphones. We’re talking about multi-threaded, high performance apps that can track your movement or even take pictures of whatever you think is interesting.
RIAs Done Right: Grails, Flex, and EXT GWTMichael Galpin
Your users want a more advanced user interface. You know that your system needs a service-oriented architecture. You're in luck! These two things actually go hand in hand. Not only can you get the best of both worlds but modern technologies and tools even make it fun to develop these systems. Find out how to build RESTful back-end systems with Grails. You can easily add a Flex front end, or you can try Ext GWT: a combination of Ext JS's rich widgets -- all on the Java™ platform, thanks to the Google Web Toolkit.
State of ICS and IoT Cyber Threat Landscape Report 2024 previewPrayukth K V
The IoT and OT threat landscape report has been prepared by the Threat Research Team at Sectrio using data from Sectrio, cyber threat intelligence farming facilities spread across over 85 cities around the world. In addition, Sectrio also runs AI-based advanced threat and payload engagement facilities that serve as sinks to attract and engage sophisticated threat actors, and newer malware including new variants and latent threats that are at an earlier stage of development.
The latest edition of the OT/ICS and IoT security Threat Landscape Report 2024 also covers:
State of global ICS asset and network exposure
Sectoral targets and attacks as well as the cost of ransom
Global APT activity, AI usage, actor and tactic profiles, and implications
Rise in volumes of AI-powered cyberattacks
Major cyber events in 2024
Malware and malicious payload trends
Cyberattack types and targets
Vulnerability exploit attempts on CVEs
Attacks on counties – USA
Expansion of bot farms – how, where, and why
In-depth analysis of the cyber threat landscape across North America, South America, Europe, APAC, and the Middle East
Why are attacks on smart factories rising?
Cyber risk predictions
Axis of attacks – Europe
Systemic attacks in the Middle East
Download the full report from here:
https://sectrio.com/resources/ot-threat-landscape-reports/sectrio-releases-ot-ics-and-iot-security-threat-landscape-report-2024/
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.
Neuro-symbolic is not enough, we need neuro-*semantic*Frank van Harmelen
Neuro-symbolic (NeSy) AI is on the rise. However, simply machine learning on just any symbolic structure is not sufficient to really harvest the gains of NeSy. These will only be gained when the symbolic structures have an actual semantics. I give an operational definition of semantics as “predictable inference”.
All of this illustrated with link prediction over knowledge graphs, but the argument is general.
Key Trends Shaping the Future of Infrastructure.pdfCheryl Hung
Keynote at DIGIT West Expo, Glasgow on 29 May 2024.
Cheryl Hung, ochery.com
Sr Director, Infrastructure Ecosystem, Arm.
The key trends across hardware, cloud and open-source; exploring how these areas are likely to mature and develop over the short and long-term, and then considering how organisations can position themselves to adapt and thrive.
Let's dive deeper into the world of ODC! Ricardo Alves (OutSystems) will join us to tell all about the new Data Fabric. After that, Sezen de Bruijn (OutSystems) will get into the details on how to best design a sturdy architecture within ODC.
Software Delivery At the Speed of AI: Inflectra Invests In AI-Powered QualityInflectra
In this insightful webinar, Inflectra explores how artificial intelligence (AI) is transforming software development and testing. Discover how AI-powered tools are revolutionizing every stage of the software development lifecycle (SDLC), from design and prototyping to testing, deployment, and monitoring.
Learn about:
• The Future of Testing: How AI is shifting testing towards verification, analysis, and higher-level skills, while reducing repetitive tasks.
• Test Automation: How AI-powered test case generation, optimization, and self-healing tests are making testing more efficient and effective.
• Visual Testing: Explore the emerging capabilities of AI in visual testing and how it's set to revolutionize UI verification.
• Inflectra's AI Solutions: See demonstrations of Inflectra's cutting-edge AI tools like the ChatGPT plugin and Azure Open AI platform, designed to streamline your testing process.
Whether you're a developer, tester, or QA professional, this webinar will give you valuable insights into how AI is shaping the future of software delivery.
UiPath Test Automation using UiPath Test Suite series, part 3DianaGray10
Welcome to UiPath Test Automation using UiPath Test Suite series part 3. In this session, we will cover desktop automation along with UI automation.
Topics covered:
UI automation Introduction,
UI automation Sample
Desktop automation flow
Pradeep Chinnala, Senior Consultant Automation Developer @WonderBotz and UiPath MVP
Deepak Rai, Automation Practice Lead, Boundaryless Group and UiPath MVP
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.
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Ramesh Iyer
In today's fast-changing business world, Companies that adapt and embrace new ideas often need help to keep up with the competition. However, fostering a culture of innovation takes much work. It takes vision, leadership and willingness to take risks in the right proportion. Sachin Dev Duggal, co-founder of Builder.ai, has perfected the art of this balance, creating a company culture where creativity and growth are nurtured at each stage.
Assuring Contact Center Experiences for Your Customers With ThousandEyes
Introduction to Scala for Java Developers
1. Scala for Java Developers
Michael Galpin, http://fupeg.blogspot.com
Tuesday, January 13, 2009
2. Scala is...
A general purpose programming language
✤
A language that runs on the Java VM
✤
Statically typed
✤
An object-oriented language
✤
No primitives or operators, but with singletons
✤
A functional language
✤
A scalable language
✤
Tuesday, January 13, 2009
3. Scala is General Purpose
Some uses of Scala
✤
Scripting
✤
Web applications
✤
Messaging
✤
Graphical User Interfaces
✤
Tuesday, January 13, 2009
4. Scala runs on the JVM
Compiles to Java bytecode
✤
Written by Martin Odersky (javac)
✤
Uses core Java heavily
✤
Can call any Java classes
✤
Can be called by any Java class
✤
Tuesday, January 13, 2009
5. Scala is Statically Typed
var name :String = quot;Hello, worldquot; ;
Tuesday, January 13, 2009
6. Scala is Statically Typed
var name = quot;Hello, worldquot; ;
Tuesday, January 13, 2009
7. Scala is Statically Typed
var name = quot;Hello, worldquot;
Tuesday, January 13, 2009
8. Scala is Statically Typed
val name = quot;Hello, worldquot;
Tuesday, January 13, 2009
9. Scala is Statically Typed
val name = quot;Hello, worldquot;
def makeList(a:String, b:String):List[String] = {
return a :: b :: Nil ;
}
Tuesday, January 13, 2009
10. Scala is Statically Typed
val name = quot;Hello, worldquot;
def makeList(a:String, b:String):List[String] = {
return a :: b :: Nil
}
Tuesday, January 13, 2009
11. Scala is Statically Typed
val name = quot;Hello, worldquot;
def makeList(a:String, b:String):List[String] = {
a :: b :: Nil
}
Tuesday, January 13, 2009
12. Scala is Statically Typed
val name = quot;Hello, worldquot;
def makeList(a:String, b:String):List[String] = a :: b :: Nil
Tuesday, January 13, 2009
13. Scala is Statically Typed
val name = quot;Hello, worldquot;
def makeList(a:String, b:String) = a :: b :: Nil
Tuesday, January 13, 2009
14. Scala is object-oriented
Classes
✤
class Computer (val clockSpeed:Double, var memory:Int, var hdd:Int, var os:String){
def this(clockSpeed:Double) = this(clockSpeed, 0, 0, null)
def addMemory(newRam:Int):Unit = {
this.memory += newRam
}
def addDrive(newHdd:Int) = {
this.hdd += newHdd
}
override def toString = clockSpeed + quot; GHz quot; + memory + quot; GB RAM quot; + hdd + quot; GB hdd quot; + os
}
Tuesday, January 13, 2009
15. Scala is object-oriented
Inheritance
✤
class Laptop(clockSpeed:Double, memory:Int, hdd:Int, val screenSize:Int, os:String) extends
Computer(clockSpeed,memory,hdd,os){
override def toString = screenSize + quot; inch screen quot; + super.toString
}
Mix-ins
✤
trait Mac{
var osVersion:String
def osx = {
osVersion match {
case quot;10.5quot; => quot;Leopardquot;
case quot;10.4quot; => quot;Tigerquot;
case _ => quot;OSXquot;
}
}
}
class MacBook(clockSpeed:Double, memory:Int, hdd:Int, os:String) extends Laptop(clockSpeed,
memory, hdd, 13, os) with Mac{
var osVersion = os
}
Tuesday, January 13, 2009
17. Scala has More Effective Java
You always override equals, hashCode, and toString ... right?
✤
Tuesday, January 13, 2009
18. Scala has More Effective Java
You always override equals, hashCode, and toString ... right?
✤
Case Classes
✤
case class Player(val name:String, val team:String, val position:String)
val tebow = Player(quot;Tim Tebowquot;,quot;Floridaquot;,quot;QBquot;)
println(tebow) // prints (Time Tebow,Florida,QB)
val clone = Player(quot;Tim Tebowquot;,quot;Floridaquot;,quot;QBquot;)
println(clone == tebow) // prints true
val set = new HashSet[Player]
set += tebow
set += clone
println(set.size) // prints 1
Tuesday, January 13, 2009
19. Scala is very object-oriented
No primitives
✤
No int, just Int
✤
No String[], just Array[String]
✤
No operators
✤
+ - * / ++ += are all just methods
✤
Create your own or overload (if not final)
✤
Tuesday, January 13, 2009
21. No Operators, Just Methods
Dots and parentheses are optional
✤
val x = 1.+(2)
val y = 1 + 2
println(x == y) // prints true
Tuesday, January 13, 2009
22. No Operators, Just Methods
Dots and parentheses are optional
✤
val x = 1.+(2)
val y = 1 + 2
println(x == y) // prints true
Sweet Syntactic Sugar
✤
val cache = new HashMap[String, String]
cache += (quot;fooquot;,quot;barquot;)
cache -= quot;fooquot;
Tuesday, January 13, 2009
23. Great for DSLs
Domain Specific Languages
✤
XML
✤
Actors
✤
Tuesday, January 13, 2009
24. XML Example: Atom
class Entry(var title:String, val link:String, val id:String, var updated:Date, var summary:String){
def toAtom =
<entry>
<link href={link}/>
<id>{id}</id>
<updated>{updated}</updated>
<summary>{summary}</summary>
</entry>
}
Tuesday, January 13, 2009
25. XML Example: Atom
class Feed(val title:String, val link:String, var updated:Date, val author:String, val id:String){
var entries:List[Entry] = Nil
def addEntry(entry:Entry){
entries = entry :: entries
}
def toAtom =
<feed>
<title>{title}</title>
<link href={link}/>
<updated>{updated}</updated>
<author>
<name>{author}</name>
</author>
<id>{id}</id>
{
val nodes = new NodeBuffer
for (entry <- entries) {
nodes &+ entry.toAtom
}
nodes
}
</feed>
}
Tuesday, January 13, 2009
26. XML Example: Atom
object Atom{
def main(args:Array[String]){
val f = new Feed(quot;Programming and Politicsquot;, quot;http://fupeg.blogspot.comquot;,
new Date(),quot;Michel Galpinquot;,quot;5819005quot;)
val e = new Entry(quot;New Scala Articlequot;,
quot;http://fupeg.blogspot.com/2008/04/new-scala-article.htmlquot;,
quot;6009113042595594848quot;, new Date(), quot;Article on Scala and XMLquot; )
f.addEntry(e)
println(f.toAtom)
}
}
Tuesday, January 13, 2009
27. XML Example: Atom
$ scalac Atom.scala
$ scala Atom
<feed>
<title>Programming and Politics</title>
<link href=quot;http://fupeg.blogspot.comquot;></link>
<updated>Tue Jan 13 11:35:51 PST 2009</updated>
<author>
<name>Michel Galpin</name>
</author>
<id>5819005</id>
<entry>
<link href=quot;http://fupeg.blogspot.com/2008/04/new-scala-article.htmlquot;></link>
<id>6009113042595594848</id>
<updated>Tue Jan 13 11:35:51 PST 2009</updated>
<summary>Scala is good</summary>
</entry>
</feed>
Tuesday, January 13, 2009
28. Singletons in Scala
Use object instead of class
✤
object ComputerStore{
def main(args:Array[String]) = {
val newton = new MacBook(2.0, 2048, 120, quot;10.5quot;)
println(newton.clockSpeed + quot; is fast!quot;)
println(quot;newton is running quot; + newton.osx)
}
}
Often used as factories a.k.a. companion objects
✤
val names = List(quot;Billquot;, quot;Davidquot;, quot;Michaelquot;)
Tuesday, January 13, 2009
29. Scala is functional
A function is an object, its definition is its apply method
✤
object DotProdct{
def apply(list1:List[Number], list2:[Number]) = {
var result = 0
for (i <- 0 until list1.size){
result += list1(i)*list2(i)
}
result
}
}
val a = List(1,2,3)
val b = List(4,5,6)
println(DotProduct(a,b)) // prints 32
Tuesday, January 13, 2009
30. Closures
Functions can be passed as parameters to other functions
✤
Scala allows for inline (anonymous) functions
✤
Still statically typed
✤
Lexically scoped (anonymous or not)
✤
Tuesday, January 13, 2009
32. Closure Examples
class Person(val firstName:String, val middleName:String, var lastName:String){
def print( formatter:(String,String,String) => String )={
val str = formatter(firstName,middleName,lastName)
println(str)
}
}
Tuesday, January 13, 2009
33. Closure Examples
class Person(val firstName:String, val middleName:String, var lastName:String){
def print( formatter:(String,String,String) => String )={
val str = formatter(firstName,middleName,lastName)
println(str)
}
}
val p = new Person(quot;Michaelquot;,quot;Davidquot;,quot;Galpinquot;)
Tuesday, January 13, 2009
34. Closure Examples
class Person(val firstName:String, val middleName:String, var lastName:String){
def print( formatter:(String,String,String) => String )={
val str = formatter(firstName,middleName,lastName)
println(str)
}
}
val p = new Person(quot;Michaelquot;,quot;Davidquot;,quot;Galpinquot;)
val sep = quot; quot;
def std(a:String,b:String,c:String) = List(a,b,c).mkString(sep)
p.print(std)
Tuesday, January 13, 2009
35. Closure Examples
class Person(val firstName:String, val middleName:String, var lastName:String){
def print( formatter:(String,String,String) => String )={
val str = formatter(firstName,middleName,lastName)
println(str)
}
}
val p = new Person(quot;Michaelquot;,quot;Davidquot;,quot;Galpinquot;)
val sep = quot; quot;
def std(a:String,b:String,c:String) = List(a,b,c).mkString(sep)
p.print(std)
val sep2 = quot;:quot;
p.print( (a,b,c) => a + sep + b + sep2 + c)
Tuesday, January 13, 2009
36. Closure Examples
class Person(val firstName:String, val middleName:String, var lastName:String){
def print( formatter:(String,String,String) => String )={
val str = formatter(firstName,middleName,lastName)
println(str)
}
}
val p = new Person(quot;Michaelquot;,quot;Davidquot;,quot;Galpinquot;)
val sep = quot; quot;
def std(a:String,b:String,c:String) = List(a,b,c).mkString(sep)
p.print(std)
val sep2 = quot;:quot;
p.print( (a,b,c) => a + sep + b + sep2 + c)
p.print(_ + sep + _ + sep2 + _)
Tuesday, January 13, 2009
38. Closures: Not Just for Golf
var nums = 1 until 100 filter(_ % 3 == 0)
Tuesday, January 13, 2009
39. Closures: Not Just for Golf
var nums = 1 until 100 filter(_ % 3 == 0)
nums.foreach(println(_))
Tuesday, January 13, 2009
40. Closures: Not Just for Golf
var nums = 1 until 100 filter(_ % 3 == 0)
nums.foreach(println(_))
nums = nums.map(2*_ + 3)
println(quot;All greater than 10? quot; + nums.forall(_ > 10))
Tuesday, January 13, 2009
41. Closures: Not Just for Golf
var nums = 1 until 100 filter(_ % 3 == 0)
nums.foreach(println(_))
nums = nums.map(2*_ + 3)
println(quot;All greater than 10? quot; + nums.forall(_ > 10))
val sum = nums.foldLeft(0)(_+_)
println(quot;sum=quot;+sum)
Tuesday, January 13, 2009
42. Closures: Not Just for Golf
var nums = 1 until 100 filter(_ % 3 == 0)
nums.foreach(println(_))
nums = nums.map(2*_ + 3)
println(quot;All greater than 10? quot; + nums.forall(_ > 10))
val sum = nums.foldLeft(0)(_+_)
println(quot;sum=quot;+sum)
val sorted = nums.toList.sort( (n,m) => {
val remN = n % 5
val remM = m % 5
remN > remM
})
sorted.foreach( (i) => println(i + quot; quot; + i % 5))
Tuesday, January 13, 2009
43. Scala: A Scalable Language
Compiles to bytecode
✤
Very close to “native” Java
✤
Sometimes faster!
✤
Tail recursion
✤
Concurrency
✤
Tuesday, January 13, 2009
44. Scala: Better Bytecode
What is the first triangle number to have at least N divisors?
Time
N
Tuesday, January 13, 2009
45. Tail Recursion: Scala Factorial
object Factorial{
val ZERO = BigInt.int2bigInt(0)
val ONE = BigInt.int2bigInt(1)
def factorial(n:BigInt):BigInt= n match {
case ZERO => ONE
case ONE => ONE
case _ => n*factorial(n-1)
}
def main(args:Array[String]){
val i = args(0).toInt
val n = BigInt.int2bigInt(i)
val start = new java.util.Date
println(factorial(n))
val duration = (new java.util.Date()).getTime - start.getTime
println(quot;duration=quot;+duration)
}
}
Tuesday, January 13, 2009
46. And in Java...
import java.math.BigInteger;
import java.util.Date;
public class Factorial{
public static BigInteger factorial(BigInteger n){
if (n.equals(BigInteger.ZERO))
return BigInteger.ONE;
else if (n.equals(BigInteger.ONE))
return BigInteger.ONE;
else
return n.multiply(factorial(n.subtract(BigInteger.ONE)));
}
public static void main(String[] args){
BigInteger n = new BigInteger(args[0]);
Date start = new Date();
System.out.println(factorial(n));
long duration = (new Date()).getTime() - start.getTime();
System.out.println(quot;duration=quot;+duration);
}
}
Tuesday, January 13, 2009
47. And the Results...
Factorial
100000
75000
Time(ms)
50000
25000
0
10000 20000 30000 50000
N
Java Scala
Tuesday, January 13, 2009
49. Scala Concurrency: Actors
Actor Model: A Different Way to Implement Concurrency
✤
Tuesday, January 13, 2009
50. Scala Concurrency: Actors
Actor Model: A Different Way to Implement Concurrency
✤
Each Object is an Actor
✤
Tuesday, January 13, 2009
51. Scala Concurrency: Actors
Actor Model: A Different Way to Implement Concurrency
✤
Each Object is an Actor
✤
Each Actor has a Mailbox
✤
Tuesday, January 13, 2009
52. Scala Concurrency: Actors
Actor Model: A Different Way to Implement Concurrency
✤
Each Object is an Actor
✤
Each Actor has a Mailbox
✤
Actors (Asynchronously) Send Messages and Receive them in their
✤
Mailbox
Tuesday, January 13, 2009
53. Scala Concurrency: Actors
Actor Model: A Different Way to Implement Concurrency
✤
Each Object is an Actor
✤
Each Actor has a Mailbox
✤
Actors (Asynchronously) Send Messages and Receive them in their
✤
Mailbox
No Shared State
✤
Tuesday, January 13, 2009
54. Why Actors: Performance
Apache (C/Threads) vs. Yaws (Erlang/Actors)
Throughput (KB/s)
Concurrent Sessions
Tuesday, January 13, 2009
55. Why Actors: Simpler Code
No Code Changes for Multi-threaded vs. Single-threaded
✤
No Mutable State
✤
No (Dead) Locking
✤
Tuesday, January 13, 2009
56. Actor Example
case object Ping
case object Pong
case object Stop
class Pong extends Actor {
def act() {
var pongCount = 0
loop {
react {
case Ping =>
if (pongCount % 1000 == 0) // print every 1000th Ping
println(quot;Pong: ping quot;+pongCount)
sender ! Pong
pongCount = pongCount + 1
case Stop =>
println(quot;Pong: stopquot;)
exit()
}
}
}
}
Tuesday, January 13, 2009
57. Actor Example
class Ping(count: Int, pong: Actor) extends Actor {
def act(){
var pingsLeft = count - 1
pong ! Ping
loop{
react {
case Pong =>
if (pingsLeft % 1000 == 0) // print every 1000th Pong
println(quot;Ping: pongquot;)
if (pingsLeft > 0){
pong ! Ping
pingsLeft -= 1
} else {
println(quot;Ping: stopquot;)
pong ! Stop
exit()
}
}
}
}
}
Tuesday, January 13, 2009
58. Actor Example
object PingPong {
def main(args:Array[String]){
val pong = new Pong
val ping = new Ping(100000, pong)
ping.start
pong.start
}
}
Tuesday, January 13, 2009