Reputation: 73
I am new to Kotlin and have been developing with the language. From Java, I am used to coding getters and setters by creating two functions. For example:
public String getName(){
return name;
}
public void setName(name){
this.name = name;
}
However, can this code be simplified in Kotlin? My code right now is:
class ClassName{
private var username: String? = null
private var photoFileName: String? = null
private var userId: String? = null
private var requestSent: Boolean? = null
fun ClassName(username: String?, photoFileName: String?, userId: String?, requestSent: Boolean?) {
this.username = username
this.photoFileName = photoFileName
this.userId = userId
this.requestSent = requestSent
}
fun getUsername(): String? {
return username
}
fun setUsername(string: String){
username = string
}
fun getPhotoFileName(): String? {
return photoFileName
}
fun setPhotoFileName(string: String){
photoFileName = string
}
fun getUserId(): String? {
return userId
}
fun setUserId(string: String){
userId = string
}
fun getRequestSent(): Boolean? {
return requestSent
}
fun setRequestSent(bool: Boolean){
requestSent = bool
}
}
Upvotes: 0
Views: 265
Reputation: 11018
Your class will get converted to this if you use data class in kotlin. All the setters and getters will be replaced by the properties.And yes you can always call them like you used to do like set and get.
data class ClassName(
var username: String,
var photoFileName: String,
var userId: String,
var requestSent: String
)
Upvotes: 2
Reputation: 11734
Here's a more enhanced version of your kotlin class
data class YourClass(
var username: String? = null,
var photoFilename: String? = null,
var userId: String? = null,
var requestSent: Boolean? = null
)
You don't have to manually create setter, getter function in Kotlin.
Upvotes: 3