Loading presentation...

Present Remotely

Send the link below via email or IM

Copy

Present to your audience

Start remote presentation

  • Invited audience members will follow you as you navigate and present
  • People invited to a presentation do not need a Prezi account
  • This link expires 10 minutes after you close the presentation
  • A maximum of 30 users can follow your presentation
  • Learn more about this feature in our knowledge base article

Do you really want to delete this prezi?

Neither you, nor the coeditors you shared it with will be able to recover it again.

DeleteCancel

Make your likes visible on Facebook?

Connect your Facebook account to Prezi and let your likes appear on your timeline.
You can change this under Settings & Account at any time.

No, thanks

Scala workshop @ Webstep

No description
by

Uzi Landsmann

on 9 December 2013

Comments (0)

Please log in to add your comment.

Report abuse

Transcript of Scala workshop @ Webstep

Note!
Scala REPL
Classes & Objects
Case Classes
Scaladoc
Traits & Mixins
Functions
Loops
Recursion
sbt
Test
start by running
scala
in the terminal
assigns results to variables
use
val
eller
var
with own variables
use autocomplete!
use command history!
functions can be defined on multiple rows
Developed by Typesafe
Object-Oriented & functionel
Runs on the JVM
Concist!
Scalable!
Scala is used by LinkedIn, EDFT, Twitter, Novell, the Guardian, Xebia, Xerox, FourSquare, Sony, Siemens, Thatcham, OPower, GridGain, AppJet, Reaktor
Compile classec:
$ scalac traits.scala
Run compiled classes:
$ scala Things
scala> 2+2
res0: Int = 4

scala> res0 * 5
res1: Int = 20

scala> import java.util.Calendar
import java.util.Calendar

scala> Calendar.getInstance.get(Calendar.HOUR)
res2: Int = 3

scala> def addOhMyGod(msg: String): String = {
| msg + " oh my god!"
| }
addOhMyGod: (msg: String)String

scala> addOhMyGod("it's late")
res3: String = it's late oh my god!
class
Contains constructors, attributes and methods
class Person(name: String)
constructor
public Person(String name)
class Person(val name: String)
getter
public String name()
class Person(var name: String)
setter
public void name(String n)
Scala
Java
class Person {
val name: String
}
class Person {
var name: String
}
X
X
X
X
X
X
X
X
X
Different variants of contructors and attributes
Inheritance
abstract class Animal(legs: Int) {
def sound: String
}
class Dog extends Animal(4) {
override def sound: String = "Voff"
}
class Cat(val name: String, var age: Int) {
var mood: String
override def toString: String = name + " (" + age + "), currently in " + mood + " mood"
}
contructor
public class Cat(String name, int age)
class definition
public class Cat{}
name field and getter
private String name;
public String name() {retrun name;}
age field, getter & setter
private int age;
public int age() {return age;}
public void age_(int age){this.age=age;}
mood field, getter & setter
private String mood;
public int mood {return mood;}
public void mood_(int mood){this.mood=mood;}
toString() override
@override public String toString(){...}
Class Anatomy
object
Contains common methods and is a starting point
object Percent {
def apply(amount: Double): Percent = new Percent(amount)
implicit def double2Percent(d: Double): Percent = Percent(d * 100)
}
factory

method
- create an instance without "new", e.g.:
val p = Percent(100)
implicit converter
- automatically conversion between different classes, e.g.:
val p1: Percent = 0.567d
val p2 = Percent(12.4) + 0.67
object MyFirstApplication {
def main(args: Array[String]){
// start the application
}
}

or:

object MySecondApplication extends App {
// start the application
}
Object Anatomy
Start an application
case classes are used to simply create immutable classes with constructors, getters (but not setters), toString, hashCode, equals etc.
val in the argument list is not needed
can inherit from other classes but should not be inherited from
Suitable for pattern matchning
Note:
Companion object must be defined in the same file as the class and must have the same name!
case class Book(name: String, price: Double)
abstract class
Animal
case class
Cat
(
name
:
String
) extends
Animal
case class
Dog
(
name
:
String
) extends
Animal

object
AnimalFarm
extends
App
{
def says(
animal
:
Animal
) {

animal
match {
case
Cat
(
name
) => println(
name
+
" says meow"
)
case
Dog
(
name
) => println(
name
+
" says voff"
)
case _ => println(
"???"
)
}
}

for (
animal
<- List(
Cat
(
"Bertil"
),
Dog
(
"Josef"
))) {
says(
animal
)
}
}
Scala workshop
Webstep
13-14 Dec 2013

http://www.scala-lang.org/api/current/
class filter
class list
o = object
c = class
t = trait
package and class/object/trait name
hierarchy
description
method filter
hierarchy filter
methods
link to code
Traits are like Java interfaces, but can also contain implementations
Usefull for small, reusable activities like logging
Can be combined (mixed) in a hierarchy
trait Logger {
import java.util.logging._
private val log = Logger.getLogger(getClass.toString)
def info(msg: String) {log.log(Level.INFO, msg)}
def error(msg: String) {log.log(Level.SEVERE, msg)}
}

trait Printer {
def printToOut(msg: String) = Console.out.println(msg)
def printToErr(msg: String) = Console.err.println(msg)
}

class HtmlReader extends
Logger

class Parser
class HtmlParser extends Parser with
Printer
class XmlParser extends Parser with
Printer
with
Logger
{
val delegate = new Parser with
Logger
}
trait Logger
trait Printer
No inheritance? Use extends even for traits
HtmlParser inherits from Parser and mixes Printer
XmlParser inherits from Parser and mixes Printer and Logger
delegate is an anonymous Parser class that mixes Logger
scala> def doStuffToInts(ints: List[Int], stuff: (Int) => Int): List[Int] = {
| for (i <- ints) yield stuff(i)
| }
doStuffToInts: (ints: List[Int], stuff: Int => Int)List[Int]

scala> def add3(i: Int): Int = i + 3
add3: (i: Int)Int

scala> def add3ToInts(list: List[Int]) = doStuffToInts(list, add3)
add3ToInts: (list: List[Int])List[Int]

scala> val list = List(1, 2, 3, 4)
list: List[Int] = List(1, 2, 3, 4)

scala> add3ToInts(list)
res7: List[Int] = List(4, 5, 6, 7)

scala> def multiplyBy5(i: Int): Int = i * 5
multiplyBy5: (i: Int)Int

scala> doStuffToInts(list, multiplyBy5)
res8: List[Int] = List(5, 10, 15, 20)
Functions in Scala can be assigned to variables and be sent as arguments, just like variables
def timesTwo(i: Int): Int = i * 2
def = function
argument with type
return type
implementation
scala> def add1(i: Int): Int = i + 1
add1: (i: Int)Int

scala> add1(2)
res10: Int = 3

scala> def increment(i: Int) = add1(i)
increment: (i: Int)Int

scala> increment(4)
res11: Int = 5

scala> List(1, 2, 3, 4).filter(_ > 2)
res12: List[Int] = List(3, 4)
Functions can receive other functions as arguments
var count = 0
while (count < 3) {
println("one more ")
count += 1
}

/*
one more
one more
one more
*/

for (count <- 0 until 3) {
println("one more again")
}

/*
one more again
one more again
one more again
*/
for (i <- 1 to 3; j <- 1 to 3) println("%d * %d = %d".format(i, j, i * j))

/*
1 * 1 = 1
1 * 2 = 2
1 * 3 = 3
2 * 1 = 2
2 * 2 = 4
2 * 3 = 6
3 * 1 = 3
3 * 2 = 6
3 * 3 = 9
*/

for (i <- 1 to 50; if (i % 13 == 0)) println(i)

/*
13
26
39
*/
for (c <- "down") println(c)

/*
d
o
w
n
*/

var numbers = for (i <- 0 to 4) yield i * 10
println(numbers)

/*
Vector(0, 10, 20, 30, 40)
*/
while loop
Seldom used
Encourages var
Simple for loop
for loop with two variables
for loop with filter
iteration over a String
(a list of characters)
yield
Create a list of the same type as the given list
The values are the result of the operation after yield
while, for, yield
Se under recursion
def fact(n: Int): Int = {
if (n == 0) 1 else n * fact(n - 1)
}
def findLast(list: List[Int]): Int = list match {
case element :: Nil => element
case _ :: tail => findLast(tail)
case _ => throw new IllegalArgumentException
}
match - case
switch on steroids
sbt is a build tool for Scala and Java projects that aims to do the basics well.
ScalaTest => http://www.scalatest.org/
Specs2 => http://etorreborre.github.com/specs2/
import
org.specs2.mutable.Specification
import
org.junit.runner.RunWith
import
org.specs2.runner.JUnitRunner
@RunWith
(classOf[
JUnitRunner
])
class
AnimalSpec
extends
Specification
{

"Cat"
should {

"have correct number of legs"
in {

Cat
(
"Bertil"
).numberOfLegs mustEqual 3
}

"make the correct sound"
in {

Cat
(
"Jonas"
).sound mustEqual
"Meow"
}

"allow changing mood"
in {
val josef =
Cat
(
"Josef"
)
josef.mood mustEqual
"sleepy"
josef.mood =
"hungry"
josef.mood mustEqual
"hungry"
}
}
}
case class
Cat
(name:
String
) {
val numberOfLegs = 4
val sound =
"Meow"
var mood =
"sleepy"
}
> test

[info] Cat should
[error]

x have correct number of legs
[error]

'4' is not equal to '3'

[info] + make the correct sound
[info] + allow changing mood
Scala
Type inference
var s = "Bertil"
val pi = 3.14
val
is approximately like final i Java
var

is a variable whos value can be changed
the type (if needed), is given after the variable (UML style)
def printSomething(message: String) {...}
Functions
def add3(x: Int): Int = x + 3
def printMsg(msg: String) {println(msg)}
No semi colons needed!Use row breaks instead
Use Scalas REPL
(read–eval–print loop)
Call functions
s.contains("Bertil")
s contains "Bertil"
Add support for specs2 and junit in sbt by writing the following after an empty row (important) in build.sbt:

libraryDependencies ++= Seq(
"org.specs2" %% "specs2" % "2.3.3" % "test",
"junit" % "junit" % "4.8.2" % "test"
)
Note!
Simple Build Tool
http://prezi.com/q8rme47c4fu5/
@uzi_landsmann
How do trolls count?
(that is, in the discworld - http://en.wikipedia.org/wiki/Discworld)
one, two, three, many
many-one, many-two, many-three, many-many
many-many-one, many-many-two, many-many-three, many-many-many
many-many-many-one, many-many-many-two, many-many-many-three, lots

Trollcount
Read The Blog Post
http://codebyexample.info/2012/04/24/trollcount-count-like-a-troll/
$ git clone git://github.com/uzilan/trollcount.git

$ git checkout tests-and-stubs
Check out the code and choose the branch
Implement

and make the tests
green
Full transcript