You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Scala属性定义中`= _`的作用及相关语法特性名称咨询

Understanding = _ 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 is null
  • For numeric types such as Int or Double, it’s 0 or 0.0 respectively
  • For Boolean, it’s false
  • 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 04:22:15