Samstag, 19. Mai 2012

STIters: Smalltalk-style collection iterators in Kotlin

Kotlin is a new kid on the JVM block. It is a relatively new statically typed JVM-based Java-compatible programming language much in the spirit of Scala. It is more concise than Java by supporting variable type inference, higher-order functions (closures), extension functions, mixins and first-class delegation, etc.  (see the Kotlin FAQ). It compiles at least as fast as Java which was one of the main reasons to abandon Scala besides making Kotlin way simpler than Scala. Being developed by JetBrains it inherits the excellent IntelliJ IDE (for which a Kotlin plugin is included in the free community edition) making you very productive writing Kotlin code.

I like the approach in Kotlin where the language designers first strive for a solution to add new functionality to the library if possible and only add it to the language in case adding a library function delivers unsatisfactory results. This is IMHO a good approach to keep a programming language coherent and clear. Basically, this is why I stopped looking into Scala some time ago and then was glad when I discovered Kotlin as Kotlin retains many of the good things in Scala.

Lately, I sat down to add my dearly missed Smalltalk collection iterators to Kotlin as a little Kotlin programming exercise (see stiters).This was good fun as extension methods in Kotlin are intuitive as they should be (basically same thing as adding a method to a class) and with the use of closures simple things remain simple as well, e.g.:

public inline fun <T> Collection<T>.select(condition : (T) -> Boolean) : Collection<T>
{
    // for brevity no source provided for newInstanceNotNull(); look at stiters for more details
    val result = newInstanceNotNull()   
    for (item in this) {
        if (condition(item))
            result.add(item)
    }
    return result
}

It is easy to see, that in the extension method above a method named select is added to the Collection class. Whereas for example in C# and Ceylon the same method would roughly look like this:

public static Collection select(this Collection input)
{
    // method body omitted for brevity
}

Here the receiver object, which is a collection, is handed in as a parameter (denoted by the this pointer in the argument list). Hence, receiver object and method parameter are swapped compared to "regular" instance methods (and this is not really intuitive).

This is how to use the select method in Kotlin:

fun main(args : Array<String>)
{
    val ints = HashSet<Int>()
    ints.add(3)
    ints.add(7)
    ints.add(12)
    ints.add(23)

    var selectResultSet = ints.select{ it < 12 }
    println(selectResultList)  // prints [3, 7]
}

Check out the stiters page for more details about this little library written in Kotlin to bring Smalltalk-style collection iterators to it.

Keine Kommentare:

Kommentar veröffentlichen