您好,登录后才能下订单哦!
密码登录
登录注册
点击 登录注册 即表示同意《亿速云用户服务条款》
# 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进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。