FP language features in Kotlin?

Kotlin’s pattern matching capabilities are a far cry of Scala’s. Though in most use cases they are very sufficient.

In Kotlin you would rely on smart casts, which indeed would mitigate Kotlin’s shortcomings on pattern matching in many cases.

Your example would look like this in Kotlin:

when (o) {
  is Node -> doSomething(o.left, o.right)
}

Of course this will not work as well for deeply nested pattern matching use cases. For example the following Scala pattern cannot be nicely expressed in Kotlin:

val simplified = arithmeticExpression match {
   case Addition(Addition(n1, n2), n3) => Addition(n1 + n2, n3)
   case o => o
}

In such cases you would need nested when expressions in Kotlin. If the nesting becomes too complex, I would usually restructure my code in ways I would not do in Scala.

3 Likes