Pure functions?

Just out of curiosity: how difficult is it to implement pure functions on the JVM for Kotlin? I guess it is not easy. Seeing that D has them and Scala not makes me wonder. Pure functions is something I personally would consider much more valuable than, say, case classes...

Regards, Oliver

1 Like

It's rather impractical to implement pure functions in a language that interoperates with Java libraries: basically, you wouldn't be able to use any Java class in such a function.

All right, I see. What I think would be extremely useful and would also suffice for most purposes is the option of declaring a class, method, and attribute as immutable (pseudo code):

immutable class Foo {
  val bar: String = “” // compiles
  var baz: Int = 0 // does not compile if class declared immutable
  immutable foo: Foo = Foo(…)
}

class Bar {
  fun foo(val baz: Baz<immutable T>) {
  // …
  }
}

The compiler ensures that any class declared immutable can only have val or again immutable attributes. Method params and variables can also be declared immutable where the compiler also verifies that the declared type is an immutable class. Eventually this could be implemented through an annotation and does not have to be part of the language. I don’t know whether that is feasible or too effortful, but immutability is to me really useful for concurrent programming.

– Oliver

No Java library out there will be immutable enough. And then, only very simple things are actually absolutely immutable. Real things are often lazy, have trasient caches etc. It all gets rather involved. Not that it was absolutely impossible to do, but it's a lot of work.