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;
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.
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.
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 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.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With