C# static, Kotlin companion object and Python inheritance differences

Since I started working for Creditas I’ve been studying Kotlin, an amazing language, very concise and full of built-in features. Although there are many concepts in common with C#, there are some differences in class instantiation that caught my attention.

C#

Let’s start with a C# example:

Can you guess the output?

The static constructor of OrderSpecific is called before Order static constructor. Kind of interesting huh?

The reason for that is that, in C#, the static constructor is called only when the class is first used. So, in this case, before calling the OrderSpecific instance constructor, the Order instance constructor is called. however, because this is the first time this class is accessed, the static constructor is called first.

Kotlin

Now, let’s compare it to the Kotlin version:

What do you think will be the output?

In Kotlin, companion objects (similar to the static in C#) are executed whenever the class is used, by either instantiating it or calling a static method of it. That’s why the first output is the base class companion init method followed by the companion subclass init method.

We can also notice that instance init method are called before the constructors

Python

Finally, take a look at this Python code:

In Python, the code execution order is slightly different. I won’t go into the details, but if you want to go further, I’d recommend that you read the book Fluent Python, it really worth it. Generally speaking, the Python interpreter (CPython) executes the file from top to bottom. That is, if you have an import statement, for example, the module that is being imported is executed before all code below it. In the same way, when the interpreter reads the class declaration statement, it executes all the code that not in the method’s body. Then, the last line (18) of the code above is executed.

We could delete line 14, which would make line 6 not be executed. Although this is possible, it not only violates LSP (Liskov Substitution Principle) in SOLID but also does not behave the way it is expected from a subclass.

Conclusion

As we could see it’s important to be aware of the execution order when instantiating Subclass with “static” code. That may vary from language to language. Not to mention that is a lot of fun to compare languages if you are a nerd. =)

Please feel free to leave a comment.

Leave a comment

search previous next tag category expand menu location phone mail time cart zoom edit close