SlideShare a Scribd company logo
Short intro to Scala and the 
Play! Framework 
50 - 60 minutes 
Last updated: Sept 2014 falmeida1988@gmail.com 
Leveraging modern programming techniques to make 
safer, faster and more predictable applications
Scala - First encounter 
def hello() = { 
println("Hello, world!") 
} 
var aMap = Map("Red" -> "Apple", "Yellow" -> "Peach") 
aMap += ("Purple" -> "Grape") 
def factorial(x: BigInt): BigInt = 
if (x == 0) 1 else x * factorial(x - 1) 
class MyClass(index: Int, name: String) 
functions 
collections 
recursive functions 
classes
Scala - Background 
● Created by Martin Odersky at EPFL in 2003 
● Aimed at overcoming Java’s weaknesses while allowing for easy migration 
for former Java developers 
● One of the few object-functional languages (also: F#) 
● One of the JVM-compliant languages (also: groovy, clojure, jruby, jython)
Scala selling points 
● Functional/Object Oriented hybrid - use one, the other, or both 
● More elegant, less painful concurrency constructs 
● Uncluttered, concise syntax 
● Seamless interoperability and compatibility with Java 
● Typing: expressive type system / static typing / type safety / type inference
Quick syntax walkthrough 
● no type declaration prior to use (due to type-inference) 
var msg = "Hello, world!" 
● braces are only needed for multiline blocks 
def max(x: Int, y: Int) = if (x > y) x else y 
def max2(x: Int, y: Int) = { 
if (x > y) x 
else y 
} 
no braces 
yes braces
Quick syntax walkthrough 
● no semicolons at the end (unless you want multiple statements) 
println(line); println(line) 
println(line) 
println(line) 
equivalent code
Quick syntax walkthrough 
● type comes after variable name (only when required or for usability) 
def max(x: Int, y: Int): Int = 
if (x > y) x else y 
val m = new HashMap[Int, String] () 
required types for 
val m1: Map[Int, String] = new HashMap() 
arguments 
optional return type 
either is acceptable 
not necessary to annotate both sides 
val m2: HashMap[Int, String] = new HashMap[Int, String] ()
Quick syntax walkthrough 
● val for immutable variables, var for mutable variables 
val msg = "Hello, world!" 
msg = "Another message!" // ERROR: reassignment to val 
var msg2 = "Hello, world!" 
msg2 = "Another message!" // no error
Quick syntax walkthrough 
● statements also return a value (if, for, while, def) - which means they are 
also expressions 
var result1 = "" 
if(marks >= 50) 
result = "passed" 
else 
result = "failed" 
val result2 = if(marks >= 50) 
"passed" 
else 
"failed" 
using if as a 
statement 
if as an expression
Quick syntax walkthrough 
● return statements are allowed but generally not needed 
def multiply(a: Int,b:Int):Int = 
return a*b 
def sum(x:Int,y:Int) = 
x + y 
def greet() = println( "Hello, world!" ) 
explicitly using return 
When no return is provided, 
last value computed by the 
function is returned 
Functions that return no 
useful values have a result 
type of Unit
Quick syntax walkthrough 
● function literals or anonymous functions 
(x: Int) => x * 2 
val double = (x: Int) => x * 2 
● example usage: as parameter to function map: 
List(1,2,3,4,5).map{ (x: Int) => x * 2 } 
//evaluates to List(2, 4, 6, 8, 10) 
a function that takes an Int 
and multiplies it by two 
function value being 
assigned to a variable 
function map takes another 
function as argument
Scala, Java Comparison 
scala class MyClass(index: Int, name: String) 
class MyClass { 
private int index; 
private String name; 
public MyClass(int index, String name) { 
this.index = index; 
this.name = name; 
} 
} 
java
Scala, Java Comparison 
scala val nameHasUpperCase = name.exists(_.isUpper) 
boolean nameHasUpperCase = false; 
for (int i = 0; i < name.length(); ++i) { 
if (Character.isUpperCase(name.charAt(i))) { 
nameHasUpperCase = true; 
break; 
} 
} 
java
Scala, Java Interoperability 
● You can use Java code in Scala as-is (i.e. no changes needed). 
● Scala classes can subclass Java classes, you can instantiate Java classes 
in Scala, you can access methods, fields (even if they are static), etc. 
● You can also use Scala code in Java projects, as long as you don’t use 
many advanced Scala concepts that are not possible in Java. 
● Similar code generated by Scala and Java usually generates the exact 
same bytecode, as can be verified using tools like javap
Environment 
● Console 
● sbt - dependency and package management 
● JVM integration 
● Typesafe products (Akka, Play, Activator, Spray, Slick, etc) 
● All of your favourite Java libraries 
● Testing suites (Unit, Integration, Acceptance, Property-based, etc) 
● Small but high-level community
Weaknesses 
● It’s a large language. Users are advised not to try to use many different 
concepts at the same time, especially when starting out. 
● Scala has a somewhat steep learning curve and its complex type system is 
powerful but hard to grasp at times. 
● Implicit conversions are useful but easily misused and may make code 
harder to understand. 
● Complex function signatures may put some off.
Play Framework 
● MVC Web Framework; supports Java and Scala 
● Created in 2007 
● Used at Linkedin, Coursera, The Guardian, etc. 
● Uses sbt for dependency management 
● As of September 2014, it has had 5000 commits by over 350 contributors. 
● The Simplest Possible Play App
Play Features 
● Play has all default features one can expect from a modern framework: 
○ MVC-based separation of concerns 
○ Support for ORMs (Java) or FRMs (Scala) 
○ Rich models with support for Forms, Validation, etc. 
○ Database Migration (called evolutions) 
○ Template engine (Scala-based) 
○ Extensive routing 
○ Support for REST-only Apps 
○ Lots of community-provided plugins 
○ Supported by Typesafe
Play - Application Layout 
app/ -- Application sources 
| assets/ -- LESS, Coffeescript sources 
| controllers/ -- Controllers 
| models/ -- Domain models 
| views/ -- Templates 
build.sbt -- Build configuration 
conf/ -- Configuration files 
| application.conf -- Main configuration file 
| routes -- Routes definition 
public/ -- Public folder (CSS, JS, etc) 
project/ -- sbt configuration files 
logs/ -- Logs 
target/ -- Generated files - ignore 
test/ -- Sources for tests
Play Framework - Examples 
● Displaying a view from a controller action 
package controllers 
import play.api._ 
import play.api.mvc._ 
object Application extends Controller { 
def index = Action { 
Ok(views.html.index("Your new application is ready.")) 
} 
} 
import libraries 
create a controller 
define actions as methods
Play Framework - Examples 
● Displaying a view with some data 
package controllers 
import models._ 
import play.api._ 
import play.api.mvc._ 
import play.api.Play.current 
object Application extends Controller { 
this method returns a List[Computer] 
def index = Action { implicit request => 
val computers = Computer .list 
Ok(views.html.web.index( "Hello! I'm the WEB!" , computers)) 
} 
} 
the Computer model was defined in 
package models (not shown here) 
instantiate a view file and feed it 
a string and a list of computers
Activator 
● Web-based IDE and project viewer, built by Typesafe 
● A large number of sample applications (templates) to study and learn from
Resources 
● Scala Programming Language (Wikipedia Article) 
● Scala official site 
● Typesafe 
● Programming in Scala Book on Amazon 
● A preset Virtual Machine for Scala/Play Development 
● Functional Programming Principles in Scala on Coursera 
● Principles of Reactive Programming on Coursera 
● Play Framework Official Website 
● ScalaJavaInterop Project 
● Play Framework (Wikipedia Article) 
● Using Scala on Heroku 
● Typesafe Activator 
● All Available Activator Templates

More Related Content

What's hot (20)

PPT
Intoduction to Play Framework
Knoldus Inc.
 
PDF
Introduction to Asynchronous scala
Stratio
 
PDF
Leveraging Open Source for Database Development: Database Version Control wit...
All Things Open
 
PDF
Java Enterprise Edition Concurrency Misconceptions
Haim Yadid
 
PPTX
Akka Actor presentation
Gene Chang
 
PDF
Servlet and JSP
Gary Yeh
 
PDF
Your First Scala Web Application using Play 2.1
Matthew Barlocker
 
PPTX
Full stack development with node and NoSQL - All Things Open - October 2017
Matthew Groves
 
PPTX
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
Stephen Chin
 
PDF
System Integration with Akka and Apache Camel
krasserm
 
PDF
Akka Cluster in Java - JCConf 2015
Jiayun Zhou
 
KEY
DjangoCon 2010 Scaling Disqus
zeeg
 
PDF
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
PDF
Advanced akka features
Grzegorz Duda
 
PDF
React Development with the MERN Stack
Troy Miles
 
PDF
Play Framework and Activator
Kevin Webber
 
PDF
Java EE 6 CDI Integrates with Spring & JSF
Jiayun Zhou
 
PPTX
Don't Wait! Develop Responsive Applications with Java EE7 Instead
WASdev Community
 
PPTX
Faster Java EE Builds with Gradle
Ryan Cuprak
 
PPTX
Core web application development
Bahaa Farouk
 
Intoduction to Play Framework
Knoldus Inc.
 
Introduction to Asynchronous scala
Stratio
 
Leveraging Open Source for Database Development: Database Version Control wit...
All Things Open
 
Java Enterprise Edition Concurrency Misconceptions
Haim Yadid
 
Akka Actor presentation
Gene Chang
 
Servlet and JSP
Gary Yeh
 
Your First Scala Web Application using Play 2.1
Matthew Barlocker
 
Full stack development with node and NoSQL - All Things Open - October 2017
Matthew Groves
 
JavaFX 2 and Scala - Like Milk and Cookies (33rd Degrees)
Stephen Chin
 
System Integration with Akka and Apache Camel
krasserm
 
Akka Cluster in Java - JCConf 2015
Jiayun Zhou
 
DjangoCon 2010 Scaling Disqus
zeeg
 
JavaCro'14 - Scala and Java EE 7 Development Experiences – Peter Pilgrim
HUJAK - Hrvatska udruga Java korisnika / Croatian Java User Association
 
Advanced akka features
Grzegorz Duda
 
React Development with the MERN Stack
Troy Miles
 
Play Framework and Activator
Kevin Webber
 
Java EE 6 CDI Integrates with Spring & JSF
Jiayun Zhou
 
Don't Wait! Develop Responsive Applications with Java EE7 Instead
WASdev Community
 
Faster Java EE Builds with Gradle
Ryan Cuprak
 
Core web application development
Bahaa Farouk
 

Viewers also liked (20)

PDF
Scala, Play Framework и SBT для быстрого прототипирования и разработки веб-пр...
Magneta AI
 
PDF
Play Framework: The Basics
Philip Langer
 
PDF
sbt, past and future / sbt, 傾向と対策
scalaconfjp
 
PDF
4º básico a semana 03 de junio al 10 de junio
Colegio Camilo Henríquez
 
PPTX
Ingles
Isaias Yañez
 
PDF
Recruit, Retain, Realize - How Third Party Transactional Data Can Power Your ...
Doug Oldfield
 
PDF
Postavte zeď mezi svoje vývojáře
Ladislav Prskavec
 
PDF
Marquette Social Listening presentation
7Summits
 
PDF
6º básico a semana 09 al 13 de mayo (1)
Colegio Camilo Henríquez
 
PPTX
807 103康八上 my comic book
Ally Lin
 
PDF
อุปกรณ์เครือข่ายงคอมพิวเตอร์
ooh Pongtorn
 
PPT
Reclaiming the idea of the University
Richard Hall
 
PDF
Scala play-framework
Abdhesh Kumar
 
PPTX
Frede space up paris 2013
Jędrzej Górski
 
PPTX
Gamification review 1
Daria Axelrod Marmer
 
PPTX
Giveandget.com
Hegedűs Zsolt
 
PPTX
User experience eBay
MariaSerrano655
 
PPTX
Introduzione a Netwrix Auditor 8.5
Maurizio Taglioretti
 
PPT
iProductive Environment Platform
Productive Environment Institute
 
PDF
Multimodal Residual Learning for Visual QA
NamHyuk Ahn
 
Scala, Play Framework и SBT для быстрого прототипирования и разработки веб-пр...
Magneta AI
 
Play Framework: The Basics
Philip Langer
 
sbt, past and future / sbt, 傾向と対策
scalaconfjp
 
4º básico a semana 03 de junio al 10 de junio
Colegio Camilo Henríquez
 
Recruit, Retain, Realize - How Third Party Transactional Data Can Power Your ...
Doug Oldfield
 
Postavte zeď mezi svoje vývojáře
Ladislav Prskavec
 
Marquette Social Listening presentation
7Summits
 
6º básico a semana 09 al 13 de mayo (1)
Colegio Camilo Henríquez
 
807 103康八上 my comic book
Ally Lin
 
อุปกรณ์เครือข่ายงคอมพิวเตอร์
ooh Pongtorn
 
Reclaiming the idea of the University
Richard Hall
 
Scala play-framework
Abdhesh Kumar
 
Frede space up paris 2013
Jędrzej Górski
 
Gamification review 1
Daria Axelrod Marmer
 
Giveandget.com
Hegedűs Zsolt
 
User experience eBay
MariaSerrano655
 
Introduzione a Netwrix Auditor 8.5
Maurizio Taglioretti
 
iProductive Environment Platform
Productive Environment Institute
 
Multimodal Residual Learning for Visual QA
NamHyuk Ahn
 
Ad

Similar to Short intro to scala and the play framework (20)

PDF
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
PDF
An Introduction to Scala for Java Developers
Miles Sabin
 
PPT
Scala Talk at FOSDEM 2009
Martin Odersky
 
PDF
Scala for Java Programmers
Eric Pederson
 
PDF
An Introduction to Scala - Blending OO and Functional Paradigms
Miles Sabin
 
PDF
Scala - core features
Łukasz Wójcik
 
PPT
Basic info on java intro
kabirmahlotra
 
PPT
Basic info on java intro
kabirmahlotra
 
PDF
Scala and jvm_languages_praveen_technologist
pmanvi
 
PDF
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
PDF
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
PDF
scalaliftoff2009.pdf
Hiroshi Ono
 
PDF
scalaliftoff2009.pdf
Hiroshi Ono
 
PDF
scalaliftoff2009.pdf
Hiroshi Ono
 
PDF
scalaliftoff2009.pdf
Hiroshi Ono
 
KEY
Scala clojure techday_2011
Thadeu Russo
 
ODP
Scala ntnu
Alf Kristian Støyle
 
KEY
JavaScript Growing Up
David Padbury
 
PPT
.NET Vs J2EE
ravikirantummala2000
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
An Introduction to Scala for Java Developers
Miles Sabin
 
Scala Talk at FOSDEM 2009
Martin Odersky
 
Scala for Java Programmers
Eric Pederson
 
An Introduction to Scala - Blending OO and Functional Paradigms
Miles Sabin
 
Scala - core features
Łukasz Wójcik
 
Basic info on java intro
kabirmahlotra
 
Basic info on java intro
kabirmahlotra
 
Scala and jvm_languages_praveen_technologist
pmanvi
 
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
Hiroshi Ono
 
scalaliftoff2009.pdf
Hiroshi Ono
 
Scala clojure techday_2011
Thadeu Russo
 
JavaScript Growing Up
David Padbury
 
.NET Vs J2EE
ravikirantummala2000
 
Ad

More from Felipe (19)

PDF
Aula rotulação automática - Automatic tagging
Felipe
 
PDF
First steps with Keras 2: A tutorial with Examples
Felipe
 
PDF
Word embeddings introdução, motivação e exemplos
Felipe
 
PDF
Cloud Certifications - Overview
Felipe
 
PDF
Elasticsearch for Data Analytics
Felipe
 
PDF
Cloudwatch: Monitoring your Services with Metrics and Alarms
Felipe
 
PDF
Cloudwatch: Monitoring your AWS services with Metrics and Alarms
Felipe
 
PDF
Online Machine Learning: introduction and examples
Felipe
 
PDF
Aws cost optimization: lessons learned, strategies, tips and tools
Felipe
 
PDF
Exemplos de uso de apache spark usando aws elastic map reduce
Felipe
 
PDF
Pré processamento de grandes dados com Apache Spark
Felipe
 
PDF
Hadoop MapReduce and Apache Spark on EMR: comparing performance for distribut...
Felipe
 
PDF
Boas práticas no desenvolvimento de software
Felipe
 
PDF
Rachinations
Felipe
 
PDF
Ausgewählte preußische Tugenden
Felipe
 
PDF
Conceitos e exemplos em versionamento de código
Felipe
 
PDF
DevOps Series: Extending vagrant with Puppet for configuration management
Felipe
 
PDF
DevOps Series: Defining and Sharing Testable Machine Configurations with vagrant
Felipe
 
PDF
D3.js 30-minute intro
Felipe
 
Aula rotulação automática - Automatic tagging
Felipe
 
First steps with Keras 2: A tutorial with Examples
Felipe
 
Word embeddings introdução, motivação e exemplos
Felipe
 
Cloud Certifications - Overview
Felipe
 
Elasticsearch for Data Analytics
Felipe
 
Cloudwatch: Monitoring your Services with Metrics and Alarms
Felipe
 
Cloudwatch: Monitoring your AWS services with Metrics and Alarms
Felipe
 
Online Machine Learning: introduction and examples
Felipe
 
Aws cost optimization: lessons learned, strategies, tips and tools
Felipe
 
Exemplos de uso de apache spark usando aws elastic map reduce
Felipe
 
Pré processamento de grandes dados com Apache Spark
Felipe
 
Hadoop MapReduce and Apache Spark on EMR: comparing performance for distribut...
Felipe
 
Boas práticas no desenvolvimento de software
Felipe
 
Rachinations
Felipe
 
Ausgewählte preußische Tugenden
Felipe
 
Conceitos e exemplos em versionamento de código
Felipe
 
DevOps Series: Extending vagrant with Puppet for configuration management
Felipe
 
DevOps Series: Defining and Sharing Testable Machine Configurations with vagrant
Felipe
 
D3.js 30-minute intro
Felipe
 

Recently uploaded (20)

PDF
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
PPTX
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
PDF
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
PPTX
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
PDF
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
PDF
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
PDF
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
PPT
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
PPTX
Digital Circuits, important subject in CS
contactparinay1
 
PDF
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
PDF
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
PDF
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
PDF
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
PPTX
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
PPTX
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
PDF
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
PDF
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
PDF
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 
Peak of Data & AI Encore AI-Enhanced Workflows for the Real World
Safe Software
 
MuleSoft MCP Support (Model Context Protocol) and Use Case Demo
shyamraj55
 
“Voice Interfaces on a Budget: Building Real-time Speech Recognition on Low-c...
Edge AI and Vision Alliance
 
Seamless Tech Experiences Showcasing Cross-Platform App Design.pptx
presentifyai
 
“NPU IP Hardware Shaped Through Software and Use-case Analysis,” a Presentati...
Edge AI and Vision Alliance
 
“Computer Vision at Sea: Automated Fish Tracking for Sustainable Fishing,” a ...
Edge AI and Vision Alliance
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
The Rise of AI and IoT in Mobile App Tech.pdf
IMG Global Infotech
 
Mastering Financial Management in Direct Selling
Epixel MLM Software
 
Ericsson LTE presentation SEMINAR 2010.ppt
npat3
 
Digital Circuits, important subject in CS
contactparinay1
 
NLJUG Speaker academy 2025 - first session
Bert Jan Schrijver
 
[Newgen] NewgenONE Marvin Brochure 1.pdf
darshakparmar
 
How do you fast track Agentic automation use cases discovery?
DianaGray10
 
AI Agents in the Cloud: The Rise of Agentic Cloud Architecture
Lilly Gracia
 
From Sci-Fi to Reality: Exploring AI Evolution
Svetlana Meissner
 
Future Tech Innovations 2025 – A TechLists Insight
TechLists
 
Future-Proof or Fall Behind? 10 Tech Trends You Can’t Afford to Ignore in 2025
DIGITALCONFEX
 
NASA A Researcher’s Guide to International Space Station : Physical Sciences ...
Dr. PANKAJ DHUSSA
 
What’s my job again? Slides from Mark Simos talk at 2025 Tampa BSides
Mark Simos
 

Short intro to scala and the play framework

  • 1. Short intro to Scala and the Play! Framework 50 - 60 minutes Last updated: Sept 2014 [email protected] Leveraging modern programming techniques to make safer, faster and more predictable applications
  • 2. Scala - First encounter def hello() = { println("Hello, world!") } var aMap = Map("Red" -> "Apple", "Yellow" -> "Peach") aMap += ("Purple" -> "Grape") def factorial(x: BigInt): BigInt = if (x == 0) 1 else x * factorial(x - 1) class MyClass(index: Int, name: String) functions collections recursive functions classes
  • 3. Scala - Background ● Created by Martin Odersky at EPFL in 2003 ● Aimed at overcoming Java’s weaknesses while allowing for easy migration for former Java developers ● One of the few object-functional languages (also: F#) ● One of the JVM-compliant languages (also: groovy, clojure, jruby, jython)
  • 4. Scala selling points ● Functional/Object Oriented hybrid - use one, the other, or both ● More elegant, less painful concurrency constructs ● Uncluttered, concise syntax ● Seamless interoperability and compatibility with Java ● Typing: expressive type system / static typing / type safety / type inference
  • 5. Quick syntax walkthrough ● no type declaration prior to use (due to type-inference) var msg = "Hello, world!" ● braces are only needed for multiline blocks def max(x: Int, y: Int) = if (x > y) x else y def max2(x: Int, y: Int) = { if (x > y) x else y } no braces yes braces
  • 6. Quick syntax walkthrough ● no semicolons at the end (unless you want multiple statements) println(line); println(line) println(line) println(line) equivalent code
  • 7. Quick syntax walkthrough ● type comes after variable name (only when required or for usability) def max(x: Int, y: Int): Int = if (x > y) x else y val m = new HashMap[Int, String] () required types for val m1: Map[Int, String] = new HashMap() arguments optional return type either is acceptable not necessary to annotate both sides val m2: HashMap[Int, String] = new HashMap[Int, String] ()
  • 8. Quick syntax walkthrough ● val for immutable variables, var for mutable variables val msg = "Hello, world!" msg = "Another message!" // ERROR: reassignment to val var msg2 = "Hello, world!" msg2 = "Another message!" // no error
  • 9. Quick syntax walkthrough ● statements also return a value (if, for, while, def) - which means they are also expressions var result1 = "" if(marks >= 50) result = "passed" else result = "failed" val result2 = if(marks >= 50) "passed" else "failed" using if as a statement if as an expression
  • 10. Quick syntax walkthrough ● return statements are allowed but generally not needed def multiply(a: Int,b:Int):Int = return a*b def sum(x:Int,y:Int) = x + y def greet() = println( "Hello, world!" ) explicitly using return When no return is provided, last value computed by the function is returned Functions that return no useful values have a result type of Unit
  • 11. Quick syntax walkthrough ● function literals or anonymous functions (x: Int) => x * 2 val double = (x: Int) => x * 2 ● example usage: as parameter to function map: List(1,2,3,4,5).map{ (x: Int) => x * 2 } //evaluates to List(2, 4, 6, 8, 10) a function that takes an Int and multiplies it by two function value being assigned to a variable function map takes another function as argument
  • 12. Scala, Java Comparison scala class MyClass(index: Int, name: String) class MyClass { private int index; private String name; public MyClass(int index, String name) { this.index = index; this.name = name; } } java
  • 13. Scala, Java Comparison scala val nameHasUpperCase = name.exists(_.isUpper) boolean nameHasUpperCase = false; for (int i = 0; i < name.length(); ++i) { if (Character.isUpperCase(name.charAt(i))) { nameHasUpperCase = true; break; } } java
  • 14. Scala, Java Interoperability ● You can use Java code in Scala as-is (i.e. no changes needed). ● Scala classes can subclass Java classes, you can instantiate Java classes in Scala, you can access methods, fields (even if they are static), etc. ● You can also use Scala code in Java projects, as long as you don’t use many advanced Scala concepts that are not possible in Java. ● Similar code generated by Scala and Java usually generates the exact same bytecode, as can be verified using tools like javap
  • 15. Environment ● Console ● sbt - dependency and package management ● JVM integration ● Typesafe products (Akka, Play, Activator, Spray, Slick, etc) ● All of your favourite Java libraries ● Testing suites (Unit, Integration, Acceptance, Property-based, etc) ● Small but high-level community
  • 16. Weaknesses ● It’s a large language. Users are advised not to try to use many different concepts at the same time, especially when starting out. ● Scala has a somewhat steep learning curve and its complex type system is powerful but hard to grasp at times. ● Implicit conversions are useful but easily misused and may make code harder to understand. ● Complex function signatures may put some off.
  • 17. Play Framework ● MVC Web Framework; supports Java and Scala ● Created in 2007 ● Used at Linkedin, Coursera, The Guardian, etc. ● Uses sbt for dependency management ● As of September 2014, it has had 5000 commits by over 350 contributors. ● The Simplest Possible Play App
  • 18. Play Features ● Play has all default features one can expect from a modern framework: ○ MVC-based separation of concerns ○ Support for ORMs (Java) or FRMs (Scala) ○ Rich models with support for Forms, Validation, etc. ○ Database Migration (called evolutions) ○ Template engine (Scala-based) ○ Extensive routing ○ Support for REST-only Apps ○ Lots of community-provided plugins ○ Supported by Typesafe
  • 19. Play - Application Layout app/ -- Application sources | assets/ -- LESS, Coffeescript sources | controllers/ -- Controllers | models/ -- Domain models | views/ -- Templates build.sbt -- Build configuration conf/ -- Configuration files | application.conf -- Main configuration file | routes -- Routes definition public/ -- Public folder (CSS, JS, etc) project/ -- sbt configuration files logs/ -- Logs target/ -- Generated files - ignore test/ -- Sources for tests
  • 20. Play Framework - Examples ● Displaying a view from a controller action package controllers import play.api._ import play.api.mvc._ object Application extends Controller { def index = Action { Ok(views.html.index("Your new application is ready.")) } } import libraries create a controller define actions as methods
  • 21. Play Framework - Examples ● Displaying a view with some data package controllers import models._ import play.api._ import play.api.mvc._ import play.api.Play.current object Application extends Controller { this method returns a List[Computer] def index = Action { implicit request => val computers = Computer .list Ok(views.html.web.index( "Hello! I'm the WEB!" , computers)) } } the Computer model was defined in package models (not shown here) instantiate a view file and feed it a string and a list of computers
  • 22. Activator ● Web-based IDE and project viewer, built by Typesafe ● A large number of sample applications (templates) to study and learn from
  • 23. Resources ● Scala Programming Language (Wikipedia Article) ● Scala official site ● Typesafe ● Programming in Scala Book on Amazon ● A preset Virtual Machine for Scala/Play Development ● Functional Programming Principles in Scala on Coursera ● Principles of Reactive Programming on Coursera ● Play Framework Official Website ● ScalaJavaInterop Project ● Play Framework (Wikipedia Article) ● Using Scala on Heroku ● Typesafe Activator ● All Available Activator Templates