Lars Triers
Lars Triers

Reputation: 167

Scala class constructor's default argument naming

I need to instantiate Scala class using reflection.

I want to use class default constructor which has arguments with default values, so I need to get these default values.

Default values in Scala are just methods in JVM, so I need to get all class methods and call only those are returns default values.

The question: I see that there are two different naming conventions for methods which returns default arg values - "apply$default$X" and "$lessinit$greater$default$X" (where X is a number of position of particular argument). What is the difference between these two? Maybe it depends on Scala version or something else?

Upvotes: 0

Views: 402

Answers (1)

Alexey Romanov
Alexey Romanov

Reputation: 170815

If you declare a case class

case class Foo(bar: Int)

then this creates both a normal class and a companion object:

class Foo(bar: Int) { // def toString, hashCode, equals 
}
object Foo {
  def apply(bar: Int) = new Foo(bar)
  // def unapply
}

Of course, if you have default parameter values, both the constructor and the apply method have to use those default values; any other behavior would be quite surprising.

So the constructor's default values are returned by $lessinit$greater$default$X methods (because the constructor's name is <init>). apply$default$X are the default values for the apply method.

For non-case classes you should only see $lessinit$greater$default$X, unless you define the apply method yourself.

Upvotes: 2

Related Questions