Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Property getter or setter expected in Kotlin

I am learning Kotlin from official docs, I am trying to create a class to do arithmetic operations.

class Sum {

    var a: Int, b: Int;

    constructor(a: Int, b: Int) {
        this.a = a
        this.b = b
    }

    fun add(): Int {
        return a + b
    }
}

I have this class, now I want to create an object of this class like

val sum = Sum(1,2)
Log.d("Sum", sum.add())

I am getting this error in Sum class:

Property getter or setter expected

on b: int; within the line var a: Int, b: Int;

like image 840
N Sharma Avatar asked May 31 '17 06:05

N Sharma


People also ask

Should I use getters and setters in Kotlin?

In programming, getters are used for getting value of the property. Similarly, setters are used for setting value of the property. In Kotlin, getters and setters are optional and are auto-generated if you do not create them in your program.

How do you set setters and getters in Kotlin?

In Kotlin, setter is used to set the value of any variable and getter is used to get the value. Getters and Setters are auto-generated in the code. Let's define a property 'name', in a class, 'Company'. The data type of 'name' is String and we shall initialize it with some default value.

What is a property in Kotlin?

Properties. Properties are the variables (to be more precise, member variables) that are declared inside a class but outside the method. Kotlin properties can be declared either as mutable using the “var” keyword or as immutable using the “val” keyword.

What is property getters and setters?

What are Getters and Setters? Getters: These are the methods used in Object-Oriented Programming (OOPS) which helps to access the private attributes from a class. Setters: These are the methods used in OOPS feature which helps to set the value to private attributes in a class.


2 Answers

var a: Int, b: Int;

Kotlin doesn't allow to have multiple declarations in one line. You have to go for:

var a: Int
var b: Int

instead. The Kotlin folks simply found the C/java practice of "int a, b, .." to be something they wish to not support in Kotlin.

like image 194
GhostCat Avatar answered Oct 15 '22 17:10

GhostCat


You are writing unnecessary code in your class.

Write short form for constructor if there is only one.

If there are properties in class, they can be defined in constructor by using val or var.

Use it like following:

class Sum (var a: Int,var b: Int){

    fun add(): Int {
        return a + b
    }
}

Do read Basic Syntax of Kotlin.

like image 44
chandil03 Avatar answered Oct 15 '22 17:10

chandil03