fredoverflow fredoverflow - 22 days ago 6
Scala Question

Does Kotlin have an identity function?

Scala has a generic

identity
function in the Predef:

def identity[A](x: A): A


Does Kotlin have a similar facility in the standard library? Of course I could simply use
{ it }
instead, but I find
identity
easier to read, and instantiating all those lambdas is a little wasteful.

I must be able to use this
identity
function in places where a function
(Foo) -> Foo
is expected, for any type
Foo
. Is such a function even possible in Kotlin's type system? (In the case of Scala, there is an implicit conversion that wraps the method inside a function object or something.)

Answer

There's no such function at the moment, but you can easily define it yourself:

fun identity<T>(x: T): T = x

If you think there are enough use cases for this function to be declared in Kotlin standard library, please file an issue at youtrack.jetbrains.com. Thanks!