Shree
Shree

Reputation: 848

Why type required when defining default parameter values?

When defining a class with default parameter values why it is required to provide the type of default parameters explicitly ?

For example:

scala> case class Person(name:String = "SomeOne")  
defined class Person

But following error is encountered when the type is not provided explicitly:

scala> case class Person(name = "SomeOne")  
<console>:1: error: ':' expected but '=' found.
   case class Person(name = "SomeOne")

Is there any reason why the type inference system cannot identify the type of the default parameter values ?

Upvotes: 2

Views: 62

Answers (1)

mavarazy
mavarazy

Reputation: 7735

In Scala all following declarations are valid

case class AnyPerson(name: Any = "SomeOne")
case class StringPerson(name: String = "SomeOne")
case class CharSequencePerson(name: CharSequence = "SomeOne")

And even this one is valid

implicit def stringToLenght(name: String) = name.length()

case class Person(name:Int = "SomeOne")

In this case name default value is 7.

So number of possible options is a sum of:

  1. All inheritance of the type
  2. All implicit conversions in the scope for the Type

Let's say by mistake in your code you are doing something like this:

val person = AnyPerson()
val anotherPerson = AnyPerson(name = person.name + 9)

In this case. Have you made an error, or you gave compiler a hint, of what real meaning of the name is?

Language can have a rule for compiler to make assumption of what developer meant. But it would make code harder to read, understand, and this would be highly error prone for the final users.

Upvotes: 3

Related Questions