https://kotlinlang.org logo
#getting-started
Title
# getting-started
d

Dron Bhattacharya

02/23/2023, 6:39 PM
Can I say this code demonstrates delegation?
Copy code
class TList(vararg task: Task) {
    private val tasks: MutableList<Task>
    init {
        tasks = mutableListOf<Task>(*task)
    }

    fun add(t: Task) = tasks.add(t)
    fun remove(t: Task) = tasks.remove(t)
    fun search(id: Int) = tasks.first { it -> it.id == id }

}
c

Chris Lee

02/23/2023, 6:41 PM
a variant of delegation, yes. TList doesn’t implement the full List interface (perhaps that is by design, it’s often good to limit the surface area). Kotlin natively supports delegation.
d

Dron Bhattacharya

02/23/2023, 6:43 PM
How can I make it more Kotline-like? Can you show me?
c

Chris Lee

02/23/2023, 6:45 PM
there are examples in the link to use as a basis for adapting your code.
d

Dron Bhattacharya

02/23/2023, 6:46 PM
ok
@Chris Lee How can I use
by
in the code that I have written?
c

Chris Lee

02/23/2023, 7:16 PM
Copy code
class TList(vararg task: String) {
    private val tasks: MutableList<String>
    init {
        tasks = mutableListOf<String>(*task)
    }

    fun add(t: String) = tasks.add(t)
    fun remove(t: String) = tasks.remove(t)
    fun search(id: String) = tasks.first { it -> it == id }

}

class TList2(someList : List<String>) : List<String> by someList {
   

}
d

Dron Bhattacharya

02/23/2023, 7:21 PM
@Chris Lee But in this case, I will not be able to limit the methods available
Can I use
by
and still, limit the available methods?
c

Chris Lee

02/23/2023, 7:26 PM
not to my knowledge. If you want to expose a subset that’s a different type as you showed in your example.
d

Dron Bhattacharya

02/23/2023, 7:27 PM
OK
2 Views