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.)
There's no such function at the moment, but you can easily define it yourself:
fun <T> identity(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!
If you need to pass the identity function as a parameter to another function, you can simply use { it }
. For example, it you have a List<List<String>> and want to flatten it to a List<String>, you could use:
list.flatMap(identity)
where identity
is the identity function. This can be written as:
list.flatMap { it }
This is equivalent to:
list.flatMap { x -> x }
The alternative would be to define the identity function somewhere, such as:
val identity: (List<String>) -> List<String> = { it }
But we can't create a generic val
, so we would have to define an identity function for each type. The solution, (as it is done in Java Function
interface) is to define it as a constant function:
fun <A> identity(): (A) -> A = { it }
and use it as:
list.flatMap(identity)
Of course, it is much easier to write:
list.flatMap { it }
Declaring an identity function once for all (that would work for all types) is not possible because it would have to be parameterized. What is possible is to use a function returning this identity function:
fun <T> identity(): (T) -> T = { it }
Although it does the job, it is not very helpful since one has now to write:
list.flatMap(identity())