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:
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
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 wroteBy extending a type
T, you can make it conform to a trait a posteriori, which free function doesn't grant you.You mean that I can to add
__hash__ func to existing struct and also add Hashable trait with this approach?If you prefer, you could always use the type as a namespace, and use
T.f(t)
Yes, tha'ts exactly the point.That makes sense, yep
Also, conditional conformance. Sometimes you can't put the
Hashable on the generic type itself: Tuple[T] is only hashable if T is hashable.