Advanced live coding scala tutorial
download as text file
$ scala
val x = 10 x = 11
var y = 2 y = 12
def printInt(y:Int) { println(y) }
def plusTwo(y:Int) = y + 2
val f = (x : Int) => x + 1
val g = () => 42
def f1(f : Int => Int) = f
def f2(f : (Int,Int) => Int) = f
f1(_ + 1) f1(_ + 1)(2) == 3
f2(_ + _) f2(_ + _)(2,3) == 5
def printHello() : Unit = println("Hello")
printHello()
printHello
1.toDouble 1 toDouble
1.+(2) == 1 + 2 (1 :: 2 :: Nil) map ( x => x+2 ) == 3 :: 4 :: Nil
Nil.::(4).::(3) == 3 :: 4 :: Nil
List("haskell", "scala", "haskell", "cal").
groupBy(x=>x).
filter(_._2.size > 1).
map(_._1) == List("haskell")
Map("eins" -> 1, "zwei" -> 2)
val m = Map() + ("eins" -> 1) + ("zwei" -> 2)
m get "zwei" == 2 m get "drei" m.getOrElse("drei",0) == 0
m.mkString("["," , ","]")
m.mkString("\n")
1.to(4) 0 to 4 by 2
for(i <- 1 to 10) println(i)
for( i <- 1 to 10 ; j <- i to 10 ; if i % 2 == 0 ) yield (i,j,i*j)
for ( (x,y) <- (10 to 4 by -2).zipWithIndex) yield (x,y)
class Foo
new Foo() new Foo
class Foo { var x = 1 }
new Foo().x == 1 new Foo.x == 1
class Foo( x : Int)
class Foo( x1 : Int) { val x = x1 }
class Foo( val x : Int) new Foo(1).x == 1
class Point(val x : Int, val y : Int){
println("constructing a point")
def this() = this(0,0)
def this(xy : Int) = this(xy,xy)
override def toString = "Point(" + x + ", " + y + ")"
}
class Foo( val x : Int) ; object Foo { def apply(x : Int) = new Foo(x) }
Foo(1).x == 1
class Foo( val x : Int)
val f = new Foo(1)
f.x f.x = 2
class Foo( var x : Int)
val f = new Foo(1)
f.x == 1
f.x = 2 f.x == 2
class Foo { val x : Int = 0 }
class Foo {
private[this] val _x : Int = 0; def x = { println("getter called") ; _x }
}
(new Foo).x
class Foo {
private[this] var _x : Int = 0;
def x = _x ;
def x_= (x : Int) : Unit = { println("setting x= " + x) ; _x = x }
}
(new Foo).x = 100
$ cat > Foo.scala
case class Foo(x:Int)
CTRL-D
$ scalac -print Foo.scala
$ scalac Foo.scala # generate .class files
$ scalap Foo # display class
$ scalap Foo$ # display object
$ javap Foo # display class
$ javap Foo$ # display object
case class Point( x : Int, y : Int)
val p = Point(1,2)
val q = p.copy( y = 100 )
p.x == q.x
p.y == 2
q.y == 100
case class Line( p : Point , q : Point)
val p1 = Point(10,10)
val p2 = Point(10,100)
val l = Line(p1,p2)
val s = l match {
case Line( Point(x1,y1), Point(x2,y2) ) => x1 + "," + y1 + " - " + x2 + ", " + y2
}
val s = l match {
case Line( _ , q@Point(x2,y2) ) => q
}
object AsInt{def unapply(s:String): Option[Int] =try{ Some(s.toInt) }catch{ case _ => None }}
"77" match { case AsInt(n) => println(n) ; case _ => println("nothing") }
object Slashes { def unapply(s : String) : Option[List[String]] = Some(s.split("/").toList) }
"a/b/c" match { case Slashes(x::y::_) => List(x,y) }
sealed abstract class Thing
case class Foo() extends Thing
case class Bar() extends Thing
def f( x : Thing) : String = x match { case Foo() => "foo" }
trait Color {
private var _color : Int = 1
def color = _color
def color_( c : Int ) = { this._color = c }
}
trait Center {
private var _center: (Int,Int) = (0,0)
def center = _center
def center_= (c : (Int,Int)) = { _center = c }
def moveBy( p : (Int, Int)) = { _center = (_center._1 + p._1, _center._2 + p._2) ; this }
}
class Shape extends Center with Color {
override def toString = "color: " + color + " center: " + center
}
val s = new Shape
s.center
s.color
s.color = 0
s moveby (10,10)
s.center
s.color
class Thing
new Thing with Color with Center
trait LoggableCenter extends Center {
override def moveBy( p: (Int,Int) ) = { println("moved by " + p) ; super.moveBy(p) }
}
class Shape extends LoggableCenter with Color {
override def toString = "color: " + color + " center: " + center
}
trait ColorPrinter {
def color : Int
def print = { println("color = " + color)}
}
val s2 = new Shape with ColorPrinter
s2.print
new Thing with Center with ColorPrinter
implicit val e = "UTF8"
def openFile(filename : String)(implicit encoding : String) = println("encoding=" + encoding)
openFile("tmp.txt")
"""\d\.\d""".r findFirstIn "Version 9.1"
val x = <dir name="home"><file name="a.txt"/><file name="b.txt" /> </dir>
x \\ "dir" \ "@name" text
x \\ "file" \\ "@name" map (_.text)
import sys.process._
val s = ("find ." #| "grep -v .hg" lines_! ) toList
val x = <dir name="hal6">{s map {f => <file name={f}/> } } </dir>
new scala.xml.PrettyPrinter(80,2).formatNodes(x)
import sys.process._
import java.io.File
"find ." #| "grep -v .svn" #> new File("files.txt") !
"echo test" #> new File("test2.txt") !
"ls " !
"cat " #< new File("test.txt") #> new File("test-dir/test2.txt") !
val logger = ProcessLogger((o: String) => println("out " + o),(e: String) => println("err " + e))
"ls . " ! logger
"ls with err " ! logger
"find ." !
"find ." #| "grep test2" ! logger
package de {
package ibacg {
class Bar
}
}
package de.ibacg {
class Bar2
object Constants { val pi = 22 / 7; }
}
package b { class B }
package a.b { class A { val x = new _root_.b.B() } }
object PackageExample {
{
import de.ibacg.Bar;
new Bar
import de.ibacg.Bar2;
new Bar2
}
{
import de.ibacg.{Bar,Bar2}
new Bar ; new Bar2 ; Constants.pi
}
{
import de.ibacg._
new Bar ; new Bar2 ; Constants.pi
}
{
import de._;
import ibacg.Bar;
new Bar
}
{
import de.ibacg.Constants._
println(pi)
}
{
import scala.collection.immutable.{Map => ImmutableMap}
import scala.collection.mutable.{Map => MutableMap}
ImmutableMap(1 -> 2)
MutableMap(3 -> 4)
}
}
$ cat >> HelloWorld.scala
object HelloWorld extends App {
println("Hello World!")
}
CTRL-D
$ scalac HelloWorld.scala
$ scala HelloWorld
Hello World!
$ scala -cp .
HelloWorld.main(new Array(0))
$ mkdir -p src/main/scala
$ mv *.scala src/main/scala
$ rm *.class
$ cat >> build.sbt
name := HelloWorld
version := 0.1
CTRL-D
$ sbt compile # compile project assuming standard maven layout
$ sbt ~compile # compile and watch src dirs for changes
$ sbt ~run # run the main; recompile and run after changes in source files
$ sbt console # start interpreter with current project on class path
|