Reputation: 31
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
Upvotes: 3
Views: 1050
Reputation: 8033
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.
Upvotes: 1
Reputation: 478
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;
}
}
Upvotes: 1