Scala 3 — Book

# 扩展方法

Language

``````case class Circle(x: Double, y: Double, radius: Double)
``````

``````object CircleHelpers {
def circumference(c: Circle): Double = c.radius * math.Pi * 2
}
``````
``````object CircleHelpers:
def circumference(c: Circle): Double = c.radius * math.Pi * 2
``````

``````val aCircle = Circle(2, 3, 5)

// without extension methods
CircleHelpers.circumference(aCircle)
``````

``````extension (c: Circle)
def circumference: Double = c.radius * math.Pi * 2
``````

• 扩展方法 `circumference` 将添加到 `Circle` 类型里
• `c: Circle` 语法允许您在扩展方法中引用变量 `c`

``````aCircle.circumference
``````

### 导入扩展方法

``````import lib.circumference

aCircle.circumference
``````

``````value circumference is not a member of Circle, but could be made available as an extension method.

The following import might fix the problem:

import lib.circumference
``````

## 讨论

`extension` 关键字声明您将要在括号中的类型上定义一个或多个扩展方法。 要在一个类型上定义多个扩展方法，请使用以下语法：

``````extension (c: Circle)
def circumference: Double = c.radius * math.Pi * 2
def diameter: Double = c.radius * 2
def area: Double = math.Pi * c.radius * c.radius
``````