Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it good that Kotlin allows the extension of existing types?

Kotlin enables the extension of existing types. For example we can do this:

fun String.replaceSpaces(): String {
    return this.replace(' ', '_')
}

val formatted = str.replaceSpaces()

However in JavaScript this is an antipattern.

Does Kotlin sidestep the issues that this causes in Javascript?

like image 490
Ole Avatar asked Dec 04 '22 21:12

Ole


2 Answers

No this is not an antipattern. In js its an antipattern because js is dynamic and therefore changing a prototype changes how code works at runtime making it an antipattern. This is also extremely dangerous based on how the in operator works and based on the fact that you can rewrite everything, so changing a prototype can affect code somewhere on your page:

Number.prototype.toString = function(){
 return "bullshit";
};

alert(""+12);

In kotlin this is not the case as kotlin is static, and all references are built at compile time. Additionally, you cant overwrite existing methods so its not dangerous at all.

like image 53
Jonas Wilms Avatar answered Dec 06 '22 12:12

Jonas Wilms


You cannot compare a prototyped language like JS with Kotlin. All extensions are resolved statically and do not modify the extended type ("receiver"). This is really important and invalidates your worry. Please have a look at the documentation to learn more about the things happening with extensions in the background (compiler).

In my opinion, you need to be cautious with extensions though. Don't allow each and every developer in a Kotlin project to add new extensions to random types. I think the project must define certain rules handling the process of defining new functions/properties on existing types, because otherwise it can get hard to read foreign code. Also there should be firm arranged locations where to put those extensions.

like image 22
s1m0nw1 Avatar answered Dec 06 '22 12:12

s1m0nw1