Scala 2 + 2 > 4

Embed Size (px)

Citation preview

Scala

Hello world

object HelloWorld { def main(args: Array[String]) { println("Hello world!") }}

public class HelloWorld { public static void main(String[] args) { System.out.println("Hello world"); }}

scala> var peaks = Map( | "Musala" -> 2925, | "Rozhen" -> 1750 | )peaks: scala.collection.immutable.Map[java.lang.String,Int] = Map(Musala -> 2925, Rozhen -> 1750)

scala> peaks += "Botev" -> 2376

scala> println(peaks)Map(Musala -> 2925, Rozhen -> 1750, Botev -> 2376)

Java

public boolean hasUpperCase(String text) { boolean hasUpperCase = false; for (int i = 0; i < text.length(); i++) { if (Character.isUpperCase(text.charAt(i))) { hasUpperCase = true; break; } } return hasUpperCase;}

Scala

def hasUpperCase(text: String) = text.exists(_.isUpperCase)

Java

public BigInteger ?????(BigInteger x) { if (x == BigInteger.ZERO) { return BigInteger.ONE; } return x.multiply( ?????(x.subtract(BigInteger.ONE)));}

Java

public BigInteger factorial(BigInteger x) { if (x == BigInteger.ZERO) { return BigInteger.ONE; } return x.multiply( factorial(x.subtract(BigInteger.ONE)));}

def factorial(x: BigInt) = if (x == 0) 1 else x * factorial(x - 1)

Scala

Java

public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } public void setName(String name) { this.name = name; } public void setAge(int age) { this.age = age; }}

class Person(var name: String, var age: int)

Scala

Turtles all the way down

http://en.wikipedia.org/wiki/Turtles_all_the_way_down

1 + 21.+(2)

1 to 8 // => Range.Inclusive(1, 8)1.to(8)

def users = { user.name } { user.password } { user.email } { boss.name } { boss.password } { boss.email }

users \ "user"

DSLs

Growing a language

http://video.google.com/videoplay?docid=-8860158196198824415

Scala specs

object HelloSpec extends Specification { "'hello world' has 11 characters" in { "hello world" size must_== 11 } "'hello world' matches 'h.* w.*'" in { "hello world" must be matching("h.* w.*") }}

object Basic extends Baysick { def main(args:Array[String]) = { 10 PRINT "Welcome to Baysick Lunar Lander v0.9" 20 LET ('dist := 100) 30 LET ('v := 1) 40 LET ('fuel := 1000) 50 LET ('mass := 1000)

60 PRINT "You are drifting towards the moon."

70 PRINT "You must decide how much fuel to burn." 80 PRINT "To accelerate enter a positive number" 90 PRINT "To decelerate a negative"

100 PRINT "Distance " % 'dist % "km, " % "Velocity " % 'v % "km/s, " % "Fuel " % 'fuel 110 INPUT 'burn 120 IF ABS('burn)