4 ms·
I use extension functions on classes I don't own to add functionality I think the class should have had or would be extremely useful for my project if a certain
by Larrikin 9y ago
I use extension functions on classes I don't own to add functionality I think the class should have had or would be extremely useful for my project if a certain type of class had the functionality. Your example would require a static utility class in Java or an object in Kotlin to use every where, the extension functions can just be inside of a kotlin file.
So the difference would be in Kotlin
object StringUtilClass() {
fun shout(s: String) = s + "!!!""
}
import StringUtilClass.*
StringUtilClass.shout("I'm mad")
vs
fun String.shout() = this + "!!!"
import StringExtensions.*
"I'm mad".shout()
Kotlin doesn't always add brand new functionality, it also strives to make it faster to read and write code.
- fauigerzigerk 9y agoThat surprises me. I would have thought that you could do this in Kotlin just as you can in Java with static import: import StringUtilClass.* shout("I'm mad")
- Larrikin 9y agoPersonally I find that less clear where shout is coming from and how to use it. It would also make autocomplete less useful as mentioned