1

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.

KMG
  • 1,433
  • 1
  • 8
  • 19

1 Answers1

3

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
}
Sweeper
  • 213,210
  • 22
  • 193
  • 313
  • Indeed.  Semicolons are very rarely needed in Kotlin; I think I've only ever used them when squeezing multiple statements on a single line (which is rarely a good idea). – gidds May 15 '21 at 09:56
  • @Sweeper thanks a lot this made the things clear now I'm coming from C and python and I thought that using semicolons should make the things more familiar and get rid of the need to use newlines to format code. Anyway, for the future is this is the only pitfall you can think of regarding such simicolons errors or there is more? – KMG May 15 '21 at 10:00
  • @Khaled [Perhaps see this question?](https://stackoverflow.com/questions/39318457/what-are-the-rules-of-semicolon-inference) – Sweeper May 15 '21 at 10:05