Hacker News new | ask | show | jobs
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.
2 comments

Also in Kotlin you can have extension methods with multiple receivers:

    class Dictionary {
       val wordList = setOf<String>()

       fun String.isWord(word): Boolean = 
          word in wordList
    }

    ...

    val myDictionary = Dictionary()
    
    with (Dictionary) {
        println("dog".isWord)
    }

    (you can skip the "with" when being inside Dictionary)
> ...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.

Or, you know, just define a plain function.

> which allow you to add new methods to any class without needing to modify the original class

No, those aren't methods, because they don't do dynamic dispatch. This is actually a problem in case you have an inheritance hierarchy and you want different behavior for a ChildClass extending a BaseClass.

Speaking of Scala, it's the only one out of the ones mentioned here that can do that based on the compile-time time, by letting you define the same extension for both ChildClass and BaseClass, but with different priorities, such that the compiler can disambiguate.

> Or, you know, just define a plain function.

My comment was about extension methods and how the name refers to different features in Java and Kotlin, so I meant "...whereas in Java [if you wanted to use the Java feature to do the same thing the Kotlin feature by the same name does] you would have to ...".

> those aren't methods

I know, they're only sugar for static methods, as I said.

Right, and I was pointing out that your comment doesn't make much sense.