KMG
KMG

Reputation: 1501

kotlin getters and setters expecting member declaration error?

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

Answers (1)

Sweeper
Sweeper

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

Related Questions