Property getter or setter expected in Kotlin

N Sharma :

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;

chandil03 :

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.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=458412&siteId=1