Kotlin是否具有身份识别功能? [英] Does Kotlin have an identity function?
问题描述
Scala在Predef中具有通用的identity
函数:
Scala has a generic identity
function in the Predef:
def identity[A](x: A): A
Kotlin在标准库中有类似的功能吗?当然,我可以简单地使用{ it }
代替,但是我发现identity
更易于阅读,并且实例化所有这些lambda有点浪费.
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.
对于任何类型的Foo
,我必须能够在需要功能(Foo) -> Foo
的地方使用此identity
函数.这样的功能在Kotlin的字体系统中甚至可能吗? (对于Scala,存在一个隐式转换,该转换将方法包装在函数对象之内.)
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
如果您认为有足够的用例可以在Kotlin标准库中声明此功能,请在 youtrack上提出问题. jetbrains.com .谢谢!
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是否具有身份识别功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!