3

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

Shamsur
  • 31
  • 2
  • Instead of commenting to thank on both answers, you should validate the one that is best answering your question. This way the question will be closed. You can also vote on both if they helped. – JonasVautherin Apr 16 '17 at 13:24

2 Answers2

1

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.

Community
  • 1
  • 1
JonasVautherin
  • 7,297
  • 6
  • 49
  • 95
1

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;
    }
}
Dibbeke
  • 468
  • 4
  • 9