1

I am initializing a variable with "this" in my initializer block and getting a warning about leaking the this reference in the constructor. I looked up the reason

Java leaking this in constructor

and reason makes sense:

Leaking the this reference in the constructor (not controller) is dangerous, especially in a multithreaded environment. This is because the object is not fully constructed until the constructor call finishes. Leaking this from the constructor thus means that the external world gets access to an object which is not yet fully constructed. This may not necessarily lead to problems in a a single-threaded program (although it is possible, but the problem is much more obvious in this case). But if this is leaked to other threads, they can actually try to do something with the object before its construction is finished, which leads to subtle and hard to find bugs.

In Java, you could call super in the constructor, then return, then initialize some variables, but not seeing how to do that in Kotlin. How can one initialize variables after class construction, in Kotlin?

the_prole
  • 7,471
  • 14
  • 64
  • 141
  • 4
    It's not clear what Java code you are trying to translate. What do you mean by "then return, then initialize some variables"? Can you show the Java code that you want to translate to kotlin, and your attempted Kotlin code that shows the warning? – Sweeper Apr 09 '21 at 00:48

0 Answers0