23
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

Short intro to scala and the play framework

Embed Size (px)

DESCRIPTION

A short introduction (with many examples) to the Scala programming language and also an introduction to using the Play! Framework for modern, safe, efffcient and reactive web applications.

Citation preview

Page 1: Short intro to scala and the play framework

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

Page 2: Short intro to scala and the play framework

Scala - First encounterdef 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

Page 3: Short intro to scala and the play framework

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)

Page 4: Short intro to scala and the play framework

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

Page 5: Short intro to scala and the play framework

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

Page 6: Short intro to scala and the play framework

Quick syntax walkthrough● no semicolons at the end (unless you want multiple statements)

println(line); println(line)

println(line)

println(line)

equivalent code

Page 7: Short intro to scala and the play framework

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] ()

val m1: Map[Int, String] = new HashMap()

val m2: HashMap[Int, String] = new HashMap[Int, String] ()

required types for arguments

optional return type

either is acceptable

not necessary to annotate both sides

Page 8: Short intro to scala and the play framework

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

Page 9: Short intro to scala and the play framework

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

Page 10: Short intro to scala and the play framework

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!")

When no return is provided, last value computed by the

function is returned

explicitly using return

Functions that return no useful values have a result type of Unit

Page 11: Short intro to scala and the play framework

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

Page 12: Short intro to scala and the play framework

Scala, Java Comparison

class MyClass {

private int index;

private String name;

public MyClass(int index, String name) {

this.index = index;

this.name = name;

}

}

class MyClass(index: Int, name: String)scala

java

Page 13: Short intro to scala and the play framework

Scala, Java Comparison

boolean nameHasUpperCase = false;

for (int i = 0; i < name.length(); ++i) {

if (Character.isUpperCase(name.charAt(i))) {

nameHasUpperCase = true;

break;

}

}

val nameHasUpperCase = name.exists(_.isUpper)scala

java

Page 14: Short intro to scala and the play framework

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

Page 15: Short intro to scala and the play framework

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

Page 16: Short intro to scala and the play framework

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.

Page 17: Short intro to scala and the play framework

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

Page 18: Short intro to scala and the play framework

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

Page 19: Short intro to scala and the play framework

Play - Application Layoutapp/ -- 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

Page 20: Short intro to scala and the play framework

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

Page 21: Short intro to scala and the play framework

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 {

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

this method returns a List[Computer]

Page 22: Short intro to scala and the play framework

Activator● Web-based IDE and project viewer, built by Typesafe

● A large number of sample applications (templates) to study and learn from

Page 23: Short intro to scala and the play framework

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