ExplicitResultTypes
This rewrite inserts type annotations for inferred public members.
Example:
- def myComplexMethod = 1.to(10).map(i => i -> i.toString).toMap
+ def myComplexMethod: Map[Int, String] = 1.to(10).map(i => i -> i.toString).toMap
Configuration
By default, only rewrite adds type annotations for public members that have non-trivial bodies.
Name | Type | Description |
---|---|---|
memberKind | List[MemberKind] | Enable/disable this rule for defs, vals or vars. |
memberVisibility | List[MemberVisibility] | Enable/disable this rule for private/protected members. |
skipSimpleDefinitions | SimpleDefinitions | If false, insert explicit result types even for simple definitions like `val x = 2` |
fatalWarnings | Boolean | If true, report and fail unexpected errors. If false, silently ignore errors to produce an explicit result type. |
rewriteStructuralTypesToNamedSubclass | Boolean | If false, disables rewriting of inferred structural types to named subclasses. Beware that this option may produce code that no longer compiles if it previously used `scala.language.reflectiveCalls` to access methods on structural types. |
onlyImplicits | Boolean | If true, adds result types only to implicit definitions. |
fetchScala3CompilerArtifactsOnVersionMismatch | Boolean | If true and the Scala 3 version Scalafix was compiled with differs from the target files' one,attempts to resolve and download compiler artifacts dynamically via Coursier. Disabled by default as this introduces a performance overhead and might not work. |
Defaults
ExplicitResultTypes.memberKind = [
Def,
Val,
Var
]
ExplicitResultTypes.memberVisibility = [
Public,
Protected
]
ExplicitResultTypes.skipSimpleDefinitions = ['Term.Ref', 'Lit', 'Term.New']
ExplicitResultTypes.fatalWarnings = false
ExplicitResultTypes.rewriteStructuralTypesToNamedSubclass = true
ExplicitResultTypes.onlyImplicits = false
ExplicitResultTypes.fetchScala3CompilerArtifactsOnVersionMismatch = false
Examples
ExplicitResultTypes.memberKind = [Def, Val, Var]
ExplicitResultTypes.memberVisibility = [Public, Protected]
ExplicitResultTypes.skipSimpleDefinitions = ['Lit', 'Term.New']
Known limitations
This rule has several known limitations, which are most likely fixable with some effort. At the time of this writing, there are no short-term plans to address these issues however.
Scala 3 support is recent and therefore not widely tested. Expect annotations to be be less precise than the ones added to sources compiled with Scala 2.x.
Imports ordering
The rewrite inserts imports at the bottom of the global import list. Users are expected to organize the imports according to the conventions of their codebase.
For example, the rewrite may produce the following diff.
import java.io.File
import scala.collection.mutable
+ import java.util.UUID
To workaround this issue use the built-in OrganizeImports
rule.
A few more workarounds:
- use https://github.com/NeQuissimus/sort-imports
- run "organize imports" refactoring in IntelliJ