# Scala中類如何使用
## 一、類的定義基礎
在Scala中,類是面向對象編程的核心構建塊。定義一個類的基本語法如下:
```scala
class ClassName {
// 類成員(字段、方法等)
}
class Person {
var name: String = "" // 可變字段
val age: Int = 0 // 不可變字段
def greet(): Unit = {
println(s"Hello, my name is $name")
}
}
Scala的主構造函數與類定義交織在一起:
class Person(var name: String, val age: Int) {
def greet(): Unit = println(s"Hi, I'm $name, $age years old")
}
var
參數生成可變字段val
參數生成不可變字段使用this
關鍵字定義:
class Person(var name: String, val age: Int) {
def this(name: String) = this(name, 0) // 必須調用主構造器
def this() = this("Anonymous")
}
class Account {
private var _balance = 0.0 // 私有字段
// Getter
def balance = _balance
// Setter
def balance_=(value: Double): Unit = {
require(value >= 0)
_balance = value
}
}
class Calculator {
def add(a: Int, b: Int): Int = a + b
// 方法重載
def add(a: Int, b: Int, c: Int): Int = a + b + c
}
class Animal(val name: String) {
def makeSound(): Unit = println("Some generic sound")
}
class Dog(name: String) extends Animal(name) {
override def makeSound(): Unit = println("Woof!")
}
abstract class Shape {
def area: Double
def perimeter: Double
}
class Circle(radius: Double) extends Shape {
override def area: Double = math.Pi * radius * radius
override def perimeter: Double = 2 * math.Pi * radius
}
Scala中的類可以有一個同名的伴生對象:
class Student(val id: Int, var name: String)
object Student {
def apply(name: String): Student = new Student(0, name)
def unapply(s: Student): Option[(Int, String)] = Some((s.id, s.name))
}
// 使用
val s = Student("Alice") // 調用apply方法
特殊的類,自動提供功能:
case class Point(x: Int, y: Int) {
def +(p: Point): Point = Point(x + p.x, y + p.y)
}
// 自動獲得:
// 1. 不可變字段
// 2. toString實現
// 3. equals/hashCode
// 4. copy方法
// 5. 伴生對象與apply
val p1 = Point(1, 2)
val p2 = p1.copy(x = 3)
class Box[T](var content: T) {
def replace(newContent: T): T = {
val old = content
content = newContent
old
}
}
val intBox = new Box[Int](42)
trait Logging {
def log(msg: String): Unit = println(s"LOG: $msg")
}
class Service extends Logging {
def execute(): Unit = {
log("Service started")
// ...
}
}
val
)通過合理使用Scala的類特性,可以構建出既安全又富有表達力的面向對象設計。 “`
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。