Scala 3 — Book

# 单例对象

Language

• 它们用于创建实用程序方法的集合。
• 伴生对象 与一个类同名二者在同一个文件里。 在此情况下，该类也称为 伴生类
• 它们用于实现 traits，再用 traits 来创建 模块

## “实用工具”方法

``````object StringUtils {
def isNullOrEmpty(s: String): Boolean = s == null || s.trim.isEmpty
def leftTrim(s: String): String = s.replaceAll("^\\s+", "")
def rightTrim(s: String): String = s.replaceAll("\\s+\$", "")
}
``````
``````object StringUtils:
def isNullOrEmpty(s: String): Boolean = s == null || s.trim.isEmpty
def leftTrim(s: String): String = s.replaceAll("^\\s+", "")
def rightTrim(s: String): String = s.replaceAll("\\s+\$", "")
``````

``````val x = StringUtils.isNullOrEmpty("")    // true
val x = StringUtils.isNullOrEmpty("a")   // false
``````

## 伴生对象

``````import scala.math._

import Circle._
}

object Circle {
private def calculateArea(radius: Double): Double =
}

val circle1 = new Circle(5.0)
circle1.area   // Double = 78.53981633974483
``````
``````import scala.math.*

import Circle.*

object Circle:
private def calculateArea(radius: Double): Double =

val circle1 = Circle(5.0)
circle1.area   // Double = 78.53981633974483
``````

## 从 traits 创建模块

``````trait AddService {
def add(a: Int, b: Int) = a + b
}

trait MultiplyService {
def multiply(a: Int, b: Int) = a * b
}

// implement those traits as a concrete object
object MathService extends AddService with MultiplyService

// use the object
import MathService._
println(multiply(2,2))   // 4
``````
``````trait AddService:
def add(a: Int, b: Int) = a + b

trait MultiplyService:
def multiply(a: Int, b: Int) = a * b

// implement those traits as a concrete object