scala(8)A Tour of Scala: Abstract Types
Abstract Types
In Scala, classes are parameterized with values and types. We can change the values and also the types of parameters in scala.
package com.sillycat.easyscala.start.tour.abstracttype
abstract class Buffer[+T] {
valelement: T
}
abstract class SeqBuffer[U, +T <: Seq[U]] extends Buffer[T] {
def length = element.length
}
object AbstractTypeTest2 extends App {
def newIntSeqBuf(e1: Int, e2: Int): SeqBuffer[Int, Seq[Int]] =
new SeqBuffer[Int, List[Int]] {
val element = List(e1, e2)
}
val buf = newIntSeqBuf(7,
println("length = " + buf.length)
println("content = " + buf.element)
}
Annotations
package examples
import java.io._
class Reader(fame: String){
private val in = new BufferedReader(new FileReader(fame))
@throws(classOf[IOException])
def read() = in.read()
}
Another example of annotation
@interface Source {
public String URL();
public String mail();
}
@Source(URL = "http://coders.com/",
mail = "
[email protected]")
class MyClass …
Or we can give a default value to the interface
@interface SourceURL {
public String value();
public String mail() default "";
}
Classes
Classes in Scala are static templates that can be instantiated into many objects at runtime.
val pt = new Point(1, 2)
Case Classes
Case classes are regular classes which export their constructor parameters and which provide a recursive decomposition mechanism via pattern matching.
abstract class Term
case class Var(name: String) extends Term
case class Fun(arg: String, body: Term) extends Term
case class App(f: Term, v:Term) extends Term
The constructor parameters of case classes are treated as public values and can be accessed directly.
val x = Var("x")
Console.println(x.name)
Predefined function classOf
classOf[T] returns a runtime representation of the Scala class type T.
object ClassReprTest {
abstractclass Bar {
type T <: AnyRef
def bar(x: T) {
println("5: " + x.getClass())
}
}
def main(args: Array[String]) {
println("1: " + args.getClass())
println("2: " + classOf[Array[String]])
new Bar {
type T = Array[String]
val x: T = args
println("3: " + x.getClass())
println("4: " + classOf[T])
}.bar(args)
}
}
Try to install and try Scalatron
I download from this URL
http://cloud.github.com/downloads/scalatron/scalatron/scalatron-1.1.0.2.zip
Unzip the file and place it to a right place.
Just double click the jar file under bin directory, and the jar file named Scalatron.jar.
And visit the 8080 port, we can play now.
References:
http://www.scala-lang.org/node/104
http://www.scala-lang.org/node/106
http://www.scala-lang.org/node/110
2~6 about syntax
http://sillycat.iteye.com/blog/1536386
http://sillycat.iteye.com/blog/1536391
http://sillycat.iteye.com/blog/1536392
http://sillycat.iteye.com/blog/1735124
http://sillycat.iteye.com/blog/1748794
http://sillycat.iteye.com/blog/1748937
http://twitter.github.com/scala_school/
http://scalatron.github.com/pages/gettingstarted.html