Reputation: 1501
I'm starting to learn kotlin but I having problem implementing getters and setters I searched online and the code for my getters and setters is the same used by many guides.
package com.test
import kotlin.Int
class Test{
var name: Int = 10;
get(){
println("getting value");
return field;
}
set(value){
println("setting value");
field = value;
}
}
fun main() {
val test = Test();
println(test.name);
}
I cant see whats wrong in this code that make kotlin compiler emit an error. I'm compiling using kotlinc proj.kt
.
Upvotes: 1
Views: 137
Reputation: 270860
You seem to really like adding semicolons, and you try to add them everywhere. However, you added them too early in this case:
var name: Int = 10;
get(){
println("getting value");
return field;
}
set(value){
println("setting value");
field = value;
}
This whole thing declares a property called name
, so there should not be a semicolon after var name: Int = 10
.
Your wrongly-added semicolon makes the parser think that the declaration for name
ends there, and so the parser expects another declaration after that. Instead of another declaration, you wrote get() { ...
, which only makes sense to the parser when you are declaring a property, but as far as the parser is concerned, you are not declaring a property at this point, as the declaration of name
is already finished by your semicolon.
If you must add a semicolon, it would be after the }
of set(value)
, like this:
var name: Int = 10
get(){
println("getting value");
return field;
}
set(value){
println("setting value");
field = value;
};
See also the grammar for a property declaration.
However, note that Kotlin coding convention says that you should omit semicolons whenever possible, so you should omit all your semicolons, like this:
var name: Int = 10
get(){
println("getting value")
return field
}
set(value){
println("setting value")
field = value
}
Upvotes: 3