# Scala類和對象

## 類基礎

class Point(xc: Int, yc: Int) {
var x: Int = xc
var y: Int = yc

def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
println ("Point x location : " + x);
println ("Point y location : " + y);
}
}

import java.io._

class Point(val xc: Int, val yc: Int) {
var x: Int = xc
var y: Int = yc

def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
println ("Point x location : " + x);
println ("Point y location : " + y);
}
}

object Demo {
def main(args: Array[String]) {
val pt = new Point(10, 20);

// Move to a new location
pt.move(10, 10);
}
}

D:\software\scala-2.12.3\bin>scalac Demo.scala

D:\software\scala-2.12.3\bin>scala Demo
Point x location : 20
Point y location : 30

D:\software\scala-2.12.3\bin>

## 擴展類

import java.io._

class Point(val xc: Int, val yc: Int) {
var x: Int = xc
var y: Int = yc

def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
println ("Point x location : " + x);
println ("Point y location : " + y);
}
}

class Location(override val xc: Int, override val yc: Int,
val zc :Int) extends Point(xc, yc){
var z: Int = zc

def move(dx: Int, dy: Int, dz: Int) {
x = x + dx
y = y + dy
z = z + dz
println ("Point x location : " + x);
println ("Point y location : " + y);
println ("Point z location : " + z);
}
}

object Demo {
def main(args: Array[String]) {
val loc = new Location(10, 20, 15);

// Move to a new location
loc.move(10, 10, 5);
}
}

D:\software\scala-2.12.3\bin>scalac Demo.scala

D:\software\scala-2.12.3\bin>scala Demo
Point x location : 20
Point y location : 30
Point z location : 20

D:\software\scala-2.12.3\bin>

## 隱性類

object <object name> {
implicit class <class name>(<Variable>: Data type) {
def <method>(): Unit =
}
}

Run.scala - 將以下程序保存在源文件：Run.scala

object Run {
implicit class IntTimes(x: Int) {
def times [A](f: =>A): Unit = {
def loop(current: Int): Unit =

if(current > 0){
f
loop(current - 1)
}
loop(x)
}
}
}

Demo.scala - 將以下程序保存在源文件：Demo.scala 中 -

import Run._

object Demo {
def main(args: Array[String]) {
4 times println("hello")
}
}

D:\software\scala-2.12.3\bin>scalac Demo.scala

D:\software\scala-2.12.3\bin>scala Demo
hello
hello
hello
hello

D:\software\scala-2.12.3\bin>

-

• 隱式類必須在另一個類/對象/特徵中定義(不在頂層)。
• 隱式類在其構造函數中只能使用一個非默認參數。
• 隱式類作用域中不可以具有與隱式類相同名稱的的任何方法，成員或對象。

## 單例對象

Scala比Java更面向對象，因爲在Scala中不能擁有靜態成員，Scala它使用單例對象。單例是一種只能有一個實例的對象。使用object關鍵字對象而不是類關鍵字創建單例。由於無法實例化單例對象，因此無法將參數傳遞給主構造函數。下面列出Scala使用單例對象的所有示例。

import java.io._

class Point(val xc: Int, val yc: Int) {
var x: Int = xc
var y: Int = yc

def move(dx: Int, dy: Int) {
x = x + dx
y = y + dy
}
}

object Demo {
def main(args: Array[String]) {
val point = new Point(10, 20)
printPoint

def printPoint{
println ("Point x location : " + point.x);
println ("Point y location : " + point.y);
}
}
}

D:\software\scala-2.12.3\bin>scalac Demo.scala

D:\software\scala-2.12.3\bin>scala Demo
Point x location : 10
Point y location : 20