I am trying to create an Interface that forces its deriving classes to have a certain property, but only with a public getter. Since I don't want to allow changes from outside its private scope, I don't want it to implement a public set.
interface Transaction{
var transferDate: Date get //I only require a get, no set
}
class MoneyTransaction(){
override var transferDate: Date get private set
/*private set does not work*/
}
In Kotlin, getters and setters are optional and are auto-generated if you do not create them in your program.
Interfaces Interfaces in Kotlin can contain declarations of abstract methods, as well as method implementations. What makes them different from abstract classes is that interfaces cannot store state. They can have properties, but these need to be abstract or provide accessor implementations.
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. By default, all properties and functions in Kotlin are public.
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.
A property is an accessor to some data. You'll have a getter and if the property is mutable a setter as well. Therefore you can override any declared val
property with a var
property:
interface Transaction {
val transferDate: Date
}
class MoneyTransaction: Transaction {
override lateinit var transferDate: Date
private set
}
Note that you don't need to make the property a lateinit var
if you initialize it with the object; I just added it to have your example compile properly.
In addition to @tynn's helpful answer, in my case I simply needed an accessor for data coming from another source. For this scenario, given that a value is being initialized with a getter, val
could be used in place of lateinit var
and there was no need to indicate private set
.
As an example in line with the others:
interface Transaction {
val transferDate: Date
}
class MostRecentTransaction(private val repo: AccountRepository) : Transaction {
override val transferDate: Date
get() = repo.transactions.first.transferDate
}
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