|
|
|
|
|
by ptx
3387 days ago
|
|
I'm no expert on Java 8, but it looks like the new feature they call "extension methods" is just the ability to define methods in interfaces and inherit them, essentially like a concrete method in an abstract base class, isn't it? The "extension methods" in Kotlin (and C#) is a completely different feature: syntactic sugar for static utility methods, which allow you to add new methods to any class without needing to modify the original class. (Or at least make it look that way syntactically.) So in Kotlin you can do this: fun String.toLeetSpeak(): String {
val charmap = mapOf('e' to '3', 'l' to '1')
return this.map { charmap[it] ?: it }.joinToString(separator="")
}
fun main(args: Array<String>) {
println("Hello!".toLeetSpeak())
}
...whereas in Java you would have to change (and have access to) the implementation of one of the classes or interfaces that String inherits from. |
|