Reputation: 848
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
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:
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