Kotlin's extension function in Mojo?

Not so long ago, I've discovered that Kotlin have a possibility to extend already defined classes with a new function. For example:
fun String.getWordsList(): List<String> {
return this.split(" ")
}

fun main() {
val text: String = "Hello world!"
val words = text.getWordsList()
println(words)
}
fun String.getWordsList(): List<String> {
return this.split(" ")
}

fun main() {
val text: String = "Hello world!"
val words = text.getWordsList()
println(words)
}
will return [Hello, world!] list. This feature is really useful, as it makes code really cleaner without overriding whole class. I don't asking Modular team to implement it. I'm just curious what others think about that. Is Mojo needs that or static methods is enough? I mean, we can use text.getWordsList() is Kotlin and get_words_list(text) in Mojo and Python. What is better for you?
7 Replies
sora
sora8mo ago
I think Mojo will have Swift style extension. See this previous answer from Modular.
Ilya I. Lubenets
Great! But is this really better to extend T and use T.do() instead of do(T)? The only usefull approach I see is ability to extend from import. Like if I do from bobby_lib import tensor_utils and somehow run it - I will get a modified Tensor struct with a bunch of new cool and useful functions that bobby wrote
sora
sora8mo ago
By extending a type T, you can make it conform to a trait a posteriori, which free function doesn't grant you.
Ilya I. Lubenets
You mean that I can to add __hash__ func to existing struct and also add Hashable trait with this approach?
sora
sora8mo ago
If you prefer, you could always use the type as a namespace, and use T.f(t) Yes, tha'ts exactly the point.
Ilya I. Lubenets
That makes sense, yep
sora
sora8mo ago
Also, conditional conformance. Sometimes you can't put the Hashable on the generic type itself: Tuple[T] is only hashable if T is hashable.
Want results from more Discord servers?
Add your server