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
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;
}
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With