Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to define accessor method for default constructor parameter?

Tags:

scala

Trying to define an accessor method for default constructor parameter, i.e.:

class Person (age: Int) {
    def age: Int = this.age
}

Which obviously results in a compiler error: ambiguous reference to overloaded definition, both method age in class Person of type => Int and value age in class Person of type Int match expected type Int

Is there a way in this context to distinguish between the member method name and auto-generated member value name?

Of course it's possible to change the name of either identifier, but is there a way in this scenario of actually specifying which identifier is referred to?

like image 512
Vlad Gudim Avatar asked Feb 24 '10 15:02

Vlad Gudim


People also ask

Is a constructor an accessor method?

Constructors initialize a new object. Accessors allow an external caller to obtain information about the state of an object. Show activity on this post. A constructor is a function responsible for object initialization.

Do accessor methods need parameters?

In Java, accessor methods return the value of a private variable. This gives other classes access to that value stored in that variable. without having direct access to the variable itself. Accessor methods take no parameters and have a return type that matches the type of the variable they are accessing.

What are mutators and accessors give examples?

In Java accessors are used to get the value of a private field and mutators are used to set the value of a private field. Accessors are also known as getters and mutators are also known as setters.

What are accessor methods?

An accessor method is an instance method that gets or sets the value of a property of an object.


1 Answers

Just put "val" in front of constructor parameters that you want to expose as instance properties.

like image 170
Randall Schulz Avatar answered Sep 23 '22 04:09

Randall Schulz