Scala属性定义中`= _`的作用及相关语法特性名称咨询
= _ in Scala's var folderName: String = _ Great question! Let's break down what this syntax does and its official name clearly.
What does = _ do?
When you declare a var (mutable variable) in Scala, the compiler enforces that every variable is initialized before it’s used. The = _ syntax tells the compiler to automatically assign the default value matching the variable’s type. Here are common examples of these default values:
- For reference types like
String, the default isnull - For numeric types such as
IntorDouble, it’s0or0.0respectively - For
Boolean, it’sfalse - For custom reference types, the default is also
null
In your code var folderName: String = _, this means folderName starts out as null until you assign a concrete string value to it later in your code.
Official Name of This Syntax
This feature is officially called Default Initialization in Scala’s documentation. You might also hear it referred to informally as Wildcard Initialization, since the underscore (_) acts as a placeholder for the default value of the declared type.
A quick caveat: This syntax only works with var variables. You can’t use = _ with val (immutable variables), because val requires an explicit, fixed initial value at the time of declaration.
内容的提问来源于stack exchange,提问作者Yuchen

