In
kotlin, member properties either initialized (or) must be declared as abstract.
Let’s see it by an example.
class Employee { private var firstName: String private var lastName: String fun getFirstName(): String { return firstName } fun getLastName(): String { return lastName } fun setFirstName(firstName: String) { this.firstName = firstName } fun setLastName(lastName: String) { this.lastName = lastName } }
Try
to compile above program, you will end up with below error.
C:\>kotlinc Employee.kt Employee.kt:2:2: error: property must be initialized or be abstract private var firstName: String ^ Employee.kt:3:2: error: property must be initialized or be abstract private var lastName: String
How to get rid of
above error?
There
are two ways, either initialize the property (or) make the property as
abstract.
Way1: Initialize the
properties firstName and lastName
Employee.kt
class Employee { private var firstName: String = "" private var lastName: String = "" fun getFirstName(): String { return firstName } fun getLastName(): String { return lastName } fun setFirstName(firstName: String) { this.firstName = firstName } fun setLastName(lastName: String) { this.lastName = lastName } }
Way 2: Make the properties
as abstract
Employee.kt
abstract class Employee { abstract var firstName: String abstract var lastName: String }
No comments:
Post a Comment