fredoverflow fredoverflow - 1 year ago 146
Scala Question

Does Kotlin have an identity function?

Scala has a generic

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
easier to read, and instantiating all those lambdas is a little wasteful.

I must be able to use this
function in places where a function
(Foo) -> Foo
is expected, for any type
. 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 Source

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 Thanks!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download