K
K
korobovn2020-07-22 10:06:34
Kotlin
korobovn, 2020-07-22 10:06:34

How to change return type for getter in Kotlin?

class Order(iitems: List<OrderItem>) {
    private val items: MutableList<OrderItem> = items.toMutableList()
}

Take an immutable OrderItem list as input, store it as mutable, and return the value as immutable.
Does not work:
class Order(items: List<OrderItem>) {
    private val items: MutableList<OrderItem> = items.toMutableList()
        get():List<OrderItem> = field.toList()
}

The language does not allow you to change the return type for a getter. With an error (Getter return type must be equal to the type of the property.)
I get around this problem as follows:
class Order(items: List<OrderItem>) {
    private val _items: MutableList<OrderItem> = items.toMutableList()

    val items: List<OrderItem>
        get() = _items.toList()
}

The code works, but Kotlin is getting verbose. Is there a way to more elegantly implement what was intended? It is possible through the classical method using simple methods, but I want to keep the style of direct access to the fields.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
illuzor, 2020-07-22
@korobovn

Normal code. Unless .toList() can be removed.
In Kotlin version 1.4, it will be possible to use delegation by property:
val items: List<OrderItem> by this::_items

A
alekseyHunter, 2020-07-22
@alekseyHunter

The code works, but Kotlin seems to get verbose in this scenario.

Why such a bike? You can pass a MutableList to the constructor right away, and when the field is called from outside, convert it back to a List.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question