Travis Griggs
12/07/2018, 7:14 PMthis. For the grins of it (because sometimes silly ideas lead to better understanding), I thought I’d try something like this:
val <Receiver>Receiver.self: Receiver get() = this
It works pretty well. I can now use self in lieu of this. Except in a few cases. One such case is in an init block:
private val manager:DownloadManager
init {
self.manager = self.context.getSystemService(Context.DOWNLOAD_SERVICE) as DownloadManager
}
It will not allow the self.manager reference there. It’s OK with the self.context.... And I can use just manager or this.manager, but for some reason my “selfish substitution” does not work there.
Enlighten me?diesieben07
12/07/2018, 7:16 PMinit block (and inside a constructor), this refers to an uninitialized instance and you are not allowed to let it "escape" (e.g. by calling some function with it).diesieben07
12/07/2018, 7:18 PMself.manager, manager is a val and thus must be initialized once and only once in a constructor or init block., The compiler cannot prove that that happens through your self indirectionTravis Griggs
12/07/2018, 7:18 PMself.context work there?Alan Evans
12/07/2018, 7:29 PMAlan Evans
12/07/2018, 7:30 PMval <Receiver>Receiver.self: Receiver get() = this
class X {
val x: Int
val y: Int = 2
init {
self.x = self.y
}
}Alan Evans
12/07/2018, 7:31 PMself is a function. The compiler can't infer that it returns this, all it knows is it is an instance of X. So it looks to it as though you are attempting to reassign to x.Alan Evans
12/07/2018, 7:32 PMself is also a function, but there is no issue reading from x here (or anywhere).Travis Griggs
12/07/2018, 7:54 PMthis gets special/contextual treatment that allows it to work. but because the self adds a level of indirection, it fails? Is that correct(ish)?Travis Griggs
12/07/2018, 7:55 PMinline ?Andreas Sinz
12/07/2018, 8:11 PMself.y shouldn't be allowed either, because its possible that y isn't initialized at the timeAndreas Sinz
12/07/2018, 8:11 PMlateinit var instead of val, but that sounds like an XY problemDico
12/08/2018, 4:56 AMAndreas Sinz
12/08/2018, 10:25 AMy is initialized after the constructor block using self as an indirectionAlan Evans
12/08/2018, 11:41 AMis a function. The compiler can't infer that it returnsself, all it knows is it is an instance ofthisX
Alan Evans
12/08/2018, 11:45 AMclass X {
init {
val x = this
x.y
}
val y: Int = 2
}
This might be why inline also has no effect on the problem.Alan Evans
12/08/2018, 11:52 AMthis and a human could even be able infer that. But a computer compiler cannot be written to determine the result of a loop (or even if the loop completes) without actually running it.
(My oversimplification of the halting problem)Travis Griggs
12/09/2018, 2:35 AMAlan Evans
12/09/2018, 1:41 PM