Kotlin Interface Property: Only require public getter without public setter
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
}
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.