Scala Classes
Classes
class MyClass(x: Int, y: Int) { // Defines a new type MyClass with a constructor
require(y > 0, "y must be positive") // precondition, triggering an IllegalArgumentException if not met
def this (x: Int) = { ... } // auxiliary constructor
def nb1 = x // public method computed every time it is called
def nb2 = y
private def test(a: Int): Int = { ... } // private method
val nb3 = x + y // computed only once
override def toString = // overridden method
member1 + ", " + member2
}
new MyClass(1, 2) // creates a new object of type
this references the current object, assert(<condition>) issues AssertionError if condition is not met. Seescala.Predef for require, assume and assert.Class hierarchies
abstract class TopLevel { // abstract class
def method1(x: Int): Int // abstract method
def method2(x: Int): Int = { ... }
}
class Level1 extends TopLevel {
def method1(x: Int): Int = { ... }
override def method2(x: Int): Int = { ...} // TopLevel's method2 needs to be explicitly overridden
}
object MyObject extends TopLevel { ... } // defines a singleton object. No other instance can be created
To create an runnable application in Scala:
object Hello {
def main(args: Array[String]) = println("Hello world")
}
orobject Hello extends App {
println("Hello World")
}
Class Organization
- General object hierarchy:
scala.Anybase type of all types. Has methodshashCodeandtoStringthat can be overloadedscala.AnyValbase type of all primitive types. (scala.Double,scala.Float, etc.)scala.AnyRefbase type of all reference types. (alias ofjava.lang.Object, supertype ofjava.lang.String,scala.List, any user-defined class)scala.Nullis a subtype of anyscala.AnyRef(nullis the only instance of typeNull), andscala.Nothingis a subtype of any other type without any instance.
评论
发表评论