Skip to content

Generated apply methods don't have default parameters #19201

Closed
@mbovel

Description

@mbovel

Reported by DallogFheir on StackOverflow.

Let person.scala be:

class Person(
    val firstName: String,
    val lastName: String,
    val birthYear: Int = -1,
    val address: String = ""
):
  // Works if remove this constructor
  def this() = this("John", "Doe")

@main
def main() =
  val p1 = Person("John", "Doe")
  val p2 = Person("Josh", "Doe", 1912, "Main Street")

Running with scala-cli run -S 3.nightly applyDefaults2.scala, we get:

[error] ./applyDefaults2.scala:11:12
[error] None of the overloaded alternatives of method apply in object Person with types
[error]  (): Person
[error]  (firstName: String, lastName: String, birthYear: Int, address: String): Person
[error] match arguments (("John" : String), ("Doe" : String))
[error]   val p1 = Person("John", "Doe")
[error]            ^^

Expectation: should work.

Possible explanations as discussed with @odersky and posted to StackOverflow:

The problem appears to stem from the interaction between universal apply methods and default parameter values. Essentially, the compiler automatically generates apply methods that forward to constructors in the companion object of classes. However, these methods do not include default parameters. Hypothesis: when there is a single constructor, the compiler is able to trace back to the original constructor's default parameters, but not when there are multiple constructors.

Metadata

Metadata

Assignees

Labels

area:desugarDesugaring happens after parsing but before typing, see desugar.scalaitype:bug

Type

No type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions