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")  
}
or
object Hello extends App {
  println("Hello World")
}

Class Organization

  • General object hierarchy:
    • scala.Any base type of all types. Has methods hashCode and toString that can be overloaded
    • scala.AnyVal base type of all primitive types. (scala.Doublescala.Float, etc.)
    • scala.AnyRef base type of all reference types. (alias of java.lang.Object, supertype of java.lang.String,scala.List, any user-defined class)
    • scala.Null is a subtype of any scala.AnyRef (null is the only instance of type Null), and scala.Nothingis a subtype of any other type without any instance.

评论

此博客中的热门博文

Nu förbjuder Kina handel med elfenben

Fader av pingyins

Kineserna vill köpa Volvos kompetens