Issue
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;
Solution
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
.
Answered By - Sachin Chandil
Answer Checked By - Mary Flores (JavaFixing Volunteer)