# 在 Scala 中提取特征

> For the complete documentation index, see [llms.txt](https://www.jetbrains.com.cn/help/idea/llms.txt).

通过   提取特征   重构，您可以将 Scala 类、对象或特征中的选定成员提取到一个新的特征中。 IntelliJ IDEA 支持  `def` 、  `val` 和  `var` 类型成员。

Procedure: 提取特征

1. 在编辑器中，选择您想要重构的代码成员。

2. 在主菜单中，前往  `重构 | 提取 | 特征` 。

或者，右键点击编辑器中的任意位置以打开上下文菜单并选择  `重构 | 特性` 。

3. 在打开的对话框中，输入一个新的 trait 名称并选择您想要提取的成员。

如果您需要选择   要提取的成员   部分中列出的所有成员，请先按 `Ctrl+A` (Windows), `⌘ A` (macOS), `⌘ A` (IntelliJ IDEA Classic (macOS)), `⌘ A` (macOS System Shortcuts), `Ctrl+A` (XWin), `Ctrl+A` (GNOME), `Ctrl+A` (KDE), `Ctrl+X, H` (Emacs), `Ctrl+A` (Sublime Text), `⌘ A` (Sublime Text (macOS)), `Ctrl+A` (Visual Studio), `⌘ A` (Visual Studio (macOS)), `Ctrl+A` (NetBeans), `Ctrl+A` (Eclipse), `⌘ A` (Eclipse (macOS)) 然后按 `Space` (Windows), `Space` (macOS), `Space` (IntelliJ IDEA Classic (macOS)), `Space` (macOS System Shortcuts), `Space` (XWin), `Space` (GNOME), `Space` (KDE), `Space` (Emacs), `Space` (Sublime Text), `Space` (Sublime Text (macOS)), `Space` (Visual Studio), `Space` (Visual Studio (macOS)), `Space` (NetBeans), `Space` (Eclipse), `Space` (Eclipse (macOS))。

点击

![提取特性对话框](https://resources.jetbrains.com.cn/help/img/idea/2026.3/extract_trait_dialog.png)   重构  。

## 示例

让我们创建一个类  `Calculator` ，并提取其中一个方法 (  `mul` ) 到一个 trait 中。

类 Calculator:

```SCALA
class Calculator {
    def add(a: Int, b: Int): Int = a + b
    def mul(a: Int, b: Int): Int = a match {
        case 0 =>0
        case _ => add(b, mul(a-1, b))
    }

}

```

方法 mul 被提取到一个新特性 Multiplier:

```SCALA
trait Multiplier {
    this: Calculator =>

    def mul(a: Int, b: Int): Int = a match {
        case 0 => 0
        case _ => add(b, mul(a - 1, b))
    }
}

```

重构后的 Class Calculator:

```SCALA
class Calculator extends Multiplier {
    def add(a: Int, b: Int): Int = a + b

}

```

IntelliJ IDEA 创建了一个新的特征  `Multiplier` ，其中包含  `mul` 方法及其定义体。 该类  `Calculator`  扩展了特质  `Multiplier` 。

## 提取特征对话框参考

|  条目  |  描述  |
| --- | --- |
|  从中提取特征  |  此字段包含您试图从中提取成员的类、对象或特征的名称。  |
|  特征名称  |  请在此字段中输入新特征的名称。  |
|  用于 trait 的包  |  使用此字段为新创建的 trait 添加一个包。 我们建议您使用与您正从中提取的原始类、对象或特征相同的包。  |
|  要提取的成员  |  请使用此区域选择您要提取的成员。    当选中  提取抽象 复选框时，新特性将仅包含声明而没有定义体。 例如，在这种情况下不包含主体的抽象方法将在原始类中被重写，并且定义将保留在那里。       当没有选中此复选框时，该方法将与其定义一起移至新的 trait，如 [example](#trait_example)中所示。     |

