Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

accessing constructor variable in companion object

Tags:

scala

Getting a compile time error for the following classes in the same file

class FancyGreeting (greeting: String) {
    //private var  greeting: String=_;

    def greet() = {
        println( "greeting in class" + greeting)
    }
}

object FancyGreeting {

    def privateGreeting(f:FancyGreeting) : String = {
        f.greeting;
    }
}

error: value greeting is not a member of this.FancyGreeting f.greeting;

The same works if i use the private variable greeting instead of the constructor

like image 372
Shamsur Avatar asked Mar 09 '26 23:03

Shamsur


2 Answers

You need to denote the constructor parameter as a variable, like so:

class FancyGreeting (val greeting: String) {
    //private var  greeting: String=_;

    def greet() = {
        println( "greeting in class" + greeting)
    }
}

object FancyGreeting {

    def privateGreeting(f:FancyGreeting) : String = {
        f.greeting;
    }
}
like image 88
Dibbeke Avatar answered Mar 11 '26 14:03

Dibbeke


You should write class FancyGreeting(private var greeting: String) { if you want to have the same behavior as when you use the line you commented out. The way you write it (i.e. class FancyGreeting(greeting: String) {) is only giving greeting as a parameter to the constructor, without making it a property.

This said, you should not use ";" to end the lines in Scala. Moreover, it is usually better to use val than var, if you can.

NOTE: this answer might be interesting for you.

like image 38
JonasVautherin Avatar answered Mar 11 '26 15:03

JonasVautherin