Scala在Predef中有一个通用的identity函数:

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

Kotlin 在标准图书馆有类似的设施吗?当然,我可以简单地使用{ it },但我发现identity更容易阅读,实例化所有这些lambda有点浪费.

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.)

推荐答案

目前还没有这样的功能,但你可以自己定义:

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!

Kotlin相关问答推荐

在Kotlin中组合多个可为空的集合

如何在Kotlin的嵌套作用域中解析对此的引用

最好的方法来创建一个 map 在kotlin从两个列表

如何将时间值格式化为00:00和00:00:00 Kotlin?""""

如何避免使用公共类实现内部接口

Kotlin编译器如何决定是否可以在任何给定点调用Suspend方法?

如何使用 Mockk 模拟返回值类的 Kotlin 函数类型?

如何在 Kotlin 中声明一个空数组而不期望 null?

顶级属性的初始化

Kotlin 编译器在构造函数中报告未使用的表达式,以便构建器采用 vararg lambda

从 Kotlin 调用 Java 时可以为空的规则是什么

T except one class

使用 Kotlin 协程时 Room dao 类出错

禁用 Android 12 默认启动画面

Kotlin-Java 互操作不能与可变参数一起使用

在 Kotlin 中实现 (/inherit/~extend) 注解

Kotlin中的下划线名称是为什么保留的?

通过在 kotlin-gradle 中使用子项目Unresolved reference: implementation

如何限制kotlin协程的最大并发性

从 Kotlin 访问 Integer.class