[Feature request] "pure" modifier

The compiler just needs to verify purity at compile time, it doesn’t need to enforce it at runtime. The JVM doesn’t understand generics either, but that didn’t prevent people from implementing them.

About Java interop, you can use the @Contract(pure = true) annotation from IntelliJ to mark a Java function as pure. Beyond that, pure Kotlin functions can be treated like regular functions in Java.

I agree that it would be almost impossible for the compiler to verify that (1..x).toList() is pure. But many Kotlin classes could be pure; inheritance is not a problem if the class is final. If an open or abstract class is pure, we could require that sub-classes must be pure as well.

That wouldn’t be very useful, since it doesn’t prevent side effects at all. It would even confuse people, because most people expect a function that’s called “pure” to be actually pure.

A better definition (IMO) of a pure class would be:

  • all properties must be val instead of var
  • all properties must be of pure types
  • all methods and getters must be pure
    • a function is pure if it doesn’t mutate any value and calls only pure functions
  • all inherited and delegated methods that aren’t abstract, must be pure
  • all inner classes and object expressions (anonymous inner classes) must be pure

Note that the companion object and nested classes don’t need to be pure, and extension methods also don’t need to be pure. However, all sub-classes must be pure.

2 Likes