Scala
Notes
function
to define a function:
def square(x:Double):Double = x * x
function literals
(x:Double) => x * x
when writing a function results Unit
type, can use a short syntax:
def foo (x:Double) { // type and '=' sign can be ignored
/** do something and return Unit type, like print */
}
to declare a new type
type Vect = (Double, Double, Double)
recursion
factorial
def fact(n:Int):Int = if (n < 2) 1 else n*fact(n-1)
read user input
readInt()
readLine()
matching
expr match {
case pattern1 => expr1
...
}
try ... catch
val num = try {
readInt()
} catch {
case 1 => ...
case e => ...
}
array and list
making array
Array(1, 2, 3, 4)
Array("one", "two", "three", "four")
Array[Double](1, 2, 3, 4) // 1.0, 2.0, 3.0, 4.0
using array
var a = Array(1, 2, 3, 4)
a(0) // 1
a.length // 4
a.size // 4
list
List(1, 2, 3, 4)
List[Int](1, 2, 3, 4)
cons operator ::
val a = List(2, 3, 4)
1::a // List (1, 2, 3, 4)
basic methods
return part of collection
drop (n:Int)
init
last
slice (from:Int, until:Int)
// until: before the given indexsplitAt (n:Int)
take (n:Int)
takeRight (n:Int)
boolean test
contains (elem:Any)
endsWith (that: Seq[B])
isEmpty
nonEmpty
startsWith
search
indexOf (elem:A)
lastIndexOf (elem:A)
others
diff (that: Seq[A])
mkString
// likeimplode
of phpreverse
toArray
,toList
zip (that: Interable[B])
zipWithIndex
higher order methods
count (P:(A) => Boolean)
dropWhile (P:(A) => Boolean)
exists (P:(A) => Boolean)
filter (P:(A) => Boolean)
filterNot (P:(A) => Boolean)
filterMap (f:(A) => Seq[B])
forall (P:(A) => Boolean)
foreach (f:(A) => Unit)
indexWhere (P:(A) => Boolean)
lastIndexWhere (P:(A) => Boolean)
map (f:(A) => B)
partition (P:(A) => Boolean)
takeWhile (P:(A) => Boolean)
combinatorial/iterator methods
combinations (n: Int)
grouped (size: Int)
inits
permutations
sliding (size: Int)
tails
loop
while(condition) statement
do { statement } while(condition)
range type:
1 to 10
1 until 10
if guards
for(...; if ...)
multiple generators
for (i <- 0 to 10; k <- 'a' to 'c') println(i + " " _+ k)
reading from file
import scala.io.Source
val fileSource = Source.fromFile("input.txt") // fileSource is a BufferedSource object
fileSource.close
fileSource.mkString // this gives a string
fileSource.mkString // this gives nothing, after 1st mkString, fileSource becomes an empty iterator
fileSource.reset // reset to iterable
reading from other source
Source.fromURL(s:string)
other options of Souce
object
hasNext():Boolean
hasNextDouble():Boolean
hasNextInt():Boolean
hasNextLine():Boolean
next():String
nextDouble()
nextInt()
nextLine()
write to file
import java.io.PrintWriter
val pw = new PrintWriter("output.txt")
for (i <- 1 to 100) {
pw.println(i)
// pw.flush
}
pw.close()
append to file
import java.io.{PrintWriter, FileWriter}
val pw = new PrintWriter(new FileWriter("output.txt", true)) // true for append
oop
class
class TypeName (arg1:Type1, arg2:Type2, ...) {
// methods and members
}
visibility
public var count = 0
private var balance = 0
protected def foo { ... }
the apply
method
arr(3) // => arr.apply(3)
the update
method
obj(args) = e // => obj.update(args, e)
property assignment method
def balance_ = {...} // write a method with the name prop_ where prop is the property name
obj.balance = 100
inheritance
class TypeName extends SuperTypeName {
override def {...}
}
calling parent methods
super.method
anonymous class
val panel = new Panel {
// methods and members
}
which is equal to
class AnonymousPanel extends Panel {
// methods and members
}
val panel = new AnonymousPanel
abstract class
abstract className (...) {
...
}
traits, just like abstract class except:
- traits ca not take arguments
- more than one traits can be inherited
trait A { ... }
trait B extends A { ... }
trait B2 extends A { ... }
class C extends B with B2 with ... { ... }
final
final class { ... }
final def { ... }
other collections
import scala.collection.immutable
import scala.collection.mutable
Set(1, 2, 3) // immutable
Map("one" -> 1, "two" -> 2) // immutable
Buffer(1, 2, 3, 4) // mutable
threads
val c = new Thread {
...
Thread.sleep(1000)
sys.exit(0)
}
synchronized
wait
/notify
Atomic
Locks
parallel collections
import scala.collection.parallel