2

A try this (in Scala 2.10.3) :

scala> class A(var a: Int = _)
<console>:1: error: unbound placeholder parameter
       class A(var a: Int = _)
                            ^

What is the problem?, the underscore for default value-type can not be used in a primary constructor?

1 Answer 1

2

The underscore is used for placeholder of the default value of the type (see Scala language specification). I am not really sure why you would want to do this type of initialization instead of: class A(var a: Int = 0) as it is likely to be more concise and other coders will know immediately the default value.

Sign up to request clarification or add additional context in comments.

5 Comments

Only testing for study the language, my question is, if a try this: scala> class A { var a: Int = _ } defined class A, then there is no problem with it, because the value of a constructor is a field for the class or not?.
When using curly braces, you're defining the body of the class. With { var a: Int _ } you've created an instance variable, a which is initialized to the default value of Int. When doing class A(var a: Int = _) you're asking scala to create an new class A which accepts an Int in it's constructor argument.
Ok, I thought the value in a constructor was created like a field so this would allow use underscore for default value :( , Thanks for you time.
You are correct, scala will provide a getter/setter for that field. For instance, class A(val myInt: Int) can later be accessed externally via: val a = new A(4); println(a.myInt). Without the val/var in the constructor argument that parameter will not be a field of the class.
Seems inconsistent that Scala programmers should only sometimes use "_" to represent the default value of a type. Anybody know why Scala language designers decided to do it this way?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.