Koan Wars: Kotlin vs TypeScript - Hamming

Koan Wars: Kotlin vs TypeScript - Hamming

Play this article

This post is the first in a series of Koan Battles, using Kotlin and TypeScript, we'll complete a Koan in both languages and then discuss the differences.

By the end of this series, you'll have a good understanding of the key features and nuances of both Kotlin and TypeScript, and be able to apply this knowledge to your own programming projects.

Whether you're a beginner or an experienced programmer, Koans provide an excellent way to learn a new language or deepen your knowledge of an existing one.

Join me as we embark on this exciting journey of discovery, enlightenment and er fighting.

Koan- Hamming Distance

Calculate the Hamming Distance between two DNA strands.

Hamming Distance is the number of positions at which the corresponding symbols in two DNA strands are different. For example:

^ ^ ^  ^ ^    ^^

They have 7 differences, and therefore the Hamming Distance is 7.

Kotlin Solution

fun compute(left: String, right: String): Int {
    require(left.length == right.length) 
        { "DNA strands must be of equal length" }

    return left.zip(right).count { it.first != it.second }

Typescript Solution

export function compute(left: string, right: string): number {
  if (left.length !== right.length)
    throw new Error("DNA strands must be of equal length");

  return [...left].filter((l, i) => l !== right[i]).length;


As you can see, the basic logic is the same in both languages: we check that the two DNA strands have the same length, and then we zip up the two arrays so they are easy to compare for the Hamming count.

One key difference between the Kotlin and TypeScript implementations is the way they handle errors. In Kotlin, we use the require function to check that the two strings have the same length, and if they don't, we throw an exception.

In TypeScript, we use a regular if statement to check the length of the strings, and if they don't have the same length, we throw an error using the throw keyword.


Overall, the two implementations are quite similar. It's close but I'll have to give this battle to Kotlin. That's more down to the use of standard library functions zip and count than the language. We could have gotten the TypeScript closer to the Kotlin solution with something like lodash.


Kotlin 1, TypeScript 0