gertell.blogg.se

Kotlin this
Kotlin this











It allows Kotlin developers to use familiar language features such as data classes, and lambda expressions as simple expressions in curly braces or method references. I can't say from your question whether A is designed for extension, which would make the C : A part correct, but you should definitely disentangle A from I.This project adds a missing layer of compatibility between Kotlin and Apache Spark.

kotlin this

For example your C.toString() may delegate to super.toString() and A.toString() ( A is the super of C) may call into I.toString(), resulting in a StackOverflowError. This may bring about all kinds of weird bugs. It doesn't expect itself as the collaborator. The class A has a dependency on a collaborator object of type I. This design suffers from other problems, not just the circular initialization dependency you are struggling with now. Your toString() implementation observes all its invariants broken, such as uninitialized vals. It has no idea it's actually calling an overridden method on itself. Later you update the library to a newer version and it happens to add something as benign as i.toString() to its constructor. You pass this like you do and things work fine. In your special case you're just storing the reference, but in just a slightly different case the superclass code might try to use the received object, which at that point is still uninitialized.Īs a specific example of why languages don't allow this, consider a case where A is a class from a library you use and this rule is not in effect. In the good tradition of OOP languages such as Java, C# or Swift, Kotlin doesn't allow you to leak the this reference before the call to superclass initialization has completed. While Kotlin could have chosen to orchestrate object initialization in a different way, it would create problems in mixed Java-Kotlin class hierarchies and add significant overhead.

kotlin this

Kotlin was born as a JVM language and aims for maximum interoperability with Java code and a minimum overhead of its language features. That's why it cannot be passed as an argument to the super-constructor. So the bytecode instruction aload 0 to push this on the stack is forbidden before the super-class constructor is called. Before that method invokes another instance initialization method of m圜lass or its direct superclass on this, the only operation the method can perform on this is assigning fields declared within m圜lass. The instance initialization method (§2.9.1) for class m圜lass sees the new uninitialized object as its this argument in local variable 0. this is only available after the super class has been initialized.













Kotlin this