Kotlin getters and setters

Hi

I Am trying to do some exercises with getters and setters.

But when I do a new project and the getter and setters become red.

The project is a console application and I tried other sorts too.

What am I doing wrong?

Code is:
fun main(args: Array) {
println(“Hello World!”)
val isEmpty: Boolean
get() = this.size == 0
}

You’ve gotta define it outside of the function like this:

val isEmpty: Boolean
    get() = this.size == 0

fun main(args: Array<String>) {
    println(“Hello World!”)
}

Also quick tip: use triple backticks (```) surrounding the code to get the correct formatting!

Thx for the quick answer :slight_smile:

So getters/setters only works only outside a fun and inside a class?

And a val/var outside a fun is called top-level?

Thx for the quick tip, didn’t know that.

1 Like