`when` with multiple arguments

enum class Direction 
{
    NORTH, SOUTH, EAST, WEST
}
...

when (firstDirection, secondDirection) 
{
  NORTH, SOUTH -> print("Switching from north to south")
  EAST, WEST -> print("Switching from east to west")
  else -> //blah blah
}

This would be nice to have for those of us that work with complex ai-oriented logic.
Is there a way to achieve something similar?

1 Like

You could use Pair

when(firstDirection to secondDirection) {
  NORTH to SOUTH -> ...

The problem with that it that it creates a lot of temporary objects which might be bad for performance depending on how often you need to call this. I personally can’t wait for the JVM to add value types, because then we could actually do this properly.

3 Likes

I also cannot wait for Value Types on the jvm. However I wonder what Kotlin’s take on value types will be, especially regarding compatibility with other platforms.

1 Like

Great idea! I will give it a try.

Jit to the rescue

  • Optimization Using Escape Analysis
    The -XX:+DoEscapeAnalysis option directs HotSpot to look for objects that are created and referenced by a single thread within the scope of a method compilation. Allocation is omitted for such non-escaping objects, and their fields are treated as local variables, often residing in machine registers. Synchronization on non-escaping objects is also elided.
4 Likes

Do you know why this feature is not enabled by default or what the downsides of it are?

It was a new feature in 2008, now Jit works out of the box as expected.

You can find more here:

https://www.ibm.com/developerworks/java/library/j-jtp09275/index.html

4 Likes

Thx, for the link. I knew that the performance of java’s garbage collector is way better than most people think but I never really knew about how it works and what kind of optimizations it does.

As indicated above, modern JVMs are very sophisticated and can do an awful lot to minimise the effect of object creation. But in my experience (of writing high-throughput systems with Java 1.6 and 1.7), there can still be big performance gains from avoiding temporary objects.

Yes, the optimiser may be able to remove or hoist some small objects. Yes, heap allocation is almost free. And yes, a short-lived object may not add any time to the next garbage collection. But if it hits the heap at all, it will make those garbage collections more frequent; and that can make a very significant difference.

So I’d be very wary of using good GC performance as a catch-all excuse for profligate use of temporary objects. They may be less costly than non-GC languages, but much of the time they’re still far from free.