https://kotlinlang.org logo
Title
g

geepawhill

07/25/2019, 5:49 PM
Folks, dumb question: Is there any way to use the delegation mechanism on a property that is not declared in the constructor? something like this:
class X : List<Y> by myList { private val myList = mutableListOf<Y>()
Failing that as a simple declaration, is the clever way to do it maybe make the primary constructor private and offer secondary constructors to call it?
h

Hanno

07/25/2019, 6:18 PM
Depends on if you need it as a property at all. If yes, then yes, private constructor. If no, just do class X: List<Y> by mutableListOf<Y> {}
k

karelpeeters

07/25/2019, 6:20 PM
This isn't really possible, which is unfortunate because it severely limits the use cases for delegates.
s

Stephan Schroeder

07/26/2019, 9:53 AM
behold the power of `invoke`:
fun main() {
	val x = X()
    x.add("done")
}

class X private constructor(list: MutableList<String>) : MutableList<String> by list {
    companion object {
        operator fun invoke(): X = X(mutableListOf())
    }
}
There might be a way to get a generic version, probably by providing a KClass to invoke. Somehow the code has to now which kind of list is meant here (your pseudo code never defines the the type either). Here the link to the playground: https://pl.kotl.in/vEGbYTUED
g

geepawhill

08/16/2019, 9:05 PM
Whoa, thanks. Excellent leads, and I will purue!