Samstag, 3. Oktober 2009

trying Scala ... 2


scala> val try1=if (1==2) 8 else 9
try1: Int = 9

scala> var total=18
total: Int = 18
scala> while(total < 17) total+=3
scala> total
res15: Int = 18

scala> for(i <- 1 to 4) println("hi five")
hi five
hi five
hi five
hi five

scala> for(i <- 1 until 5 ; j <- 1 to 3) println(i,j)
(1,1)
(1,2)
(1,3)
(2,1)
(2,2)
(2,3)
(3,1)
(3,2)
(3,3)
(4,1)
(4,2)
(4,3)

scala> for(c<-"hello")println(c)
h
e
l
l
o


hex, octal, bin is the same as in java


scala> val abyte: Byte = 27
abyte: Byte = 27


scala> var chr='A'
chr: Char = A
scala> chr=5
chr: Char =
scala> chr=66
chr: Char = B


define functions:

scala> def max(x: Int, y: Int): Int = {
| if (x > y) x
| else y
| }
max: (Int,Int)Int

scala> max(6,7)
res22: Int = 7

scala> max(3.6, 4)
:6: error: type mismatch;
found : Double(3.6)
required: Int
max(3.6, 4)



define a class


scala> class Point {
| var x=0
| var y=0
| }
defined class Point


scala> val p=new Point
p: Point = Point@18b62e0

scala> p.x=3
scala> p.y=4


scala> class Point( ix:Int,iy:Int){
| var x=ix
| var y=iy
| def vectorAdd(newpt:Point):Point={
| new Point(x+newpt.x,y+newpt.y)
| }
| }
defined class Point

scala> val p1=new Point(3,4)
p1: Point = Point@75455c
scala> val p2=new Point(7,2)
p2: Point = Point@1ba3523
scala> val p3=p1.vectorAdd(p2)
p3: Point = Point@1095c6c
scala> println(p3.x,p3.y)
(10,6)


scala> class Point( ix:Int,iy:Int){
| var x=ix
| var y=iy
| def +(newpt:Point):Point={
| new Point(x+newpt.x,y+newpt.y)
| }
| def -(newpt:Point):Point={
| new Point(x-newpt.x,y-newpt.y)
| }
| override def toString="Point("+x+","+y+")"
| }
defined class Point

scala> val p1=new Point(3,4)
p1: Point = Point(3,4)
scala> val p2=new Point(7,2)
p2: Point = Point(7,2)
scala> val p3=new Point(-2,2)
p3: Point = Point(-2,2)

scala> val p4=p1+p2-p3
p4: Point = Point(12,4)
scala> println(p4.x,p4.y)
(12,4)


there is no switch -> use match

scala> def decode(n:Int){
| n match {
| case 1 => println("One")
| case 2 => println("Two")
| case 5 => println("Five")
| case _ => println("Error")
| }
| }
decode: (Int)Unit









Keine Kommentare:

Kommentar veröffentlichen