在lambda文字上指定接收方,而无需类型推断

编程入门 行业动态 更新时间:2024-10-23 19:24:59
本文介绍了在lambda文字上指定接收方,而无需类型推断的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

假设我想要一个类型为Foo.()->Unit

Suppose I want a lambda expression which has the type of Foo.()->Unit

很明显,我可以依靠类型推断来指定它,以便lambda捕获收件人类型:val myLambda: Foo.()->Unit = { ... }

Obviously I can specify it by relying on type inference, such that the lambda captures the recipient type: val myLambda: Foo.()->Unit = { ... }

我的直觉是我可以做类似的事情:val myLambda = Foo.{ ... }

My intuition was that I could do something like: val myLambda = Foo.{ ... }

但这似乎不起作用.似乎不依靠lhs的类型推断就无法表达特定类型的lambda值似乎很奇怪.

But that doesn't appear to work. It seems weird that I can't express a lambda value of a particular type without depending on type inference from the lhs.

有我不知道的语法吗?

推荐答案

没有语法可以完全满足您的需求.正如您已经布置的那样,您可以创建一个以Foo作为其接收者的lambda,方法是在将其传递给采用此类lambda的函数时创建它:

There is no syntax that does precisely what you're looking for. As you've already laid it out, you can create a lambda that has Foo as its receiver either by creating it as you're passing it into a function that takes such a lambda:

fun useFooExtension(fooExtension: Foo.() -> Unit) { fooExtension(Foo()) } useFooExtension { println(this is Foo) }

或者通过显式指定变量的类型,例如:

Or by specifying the type of the variable explicitly, like so:

var foo1: Foo.() -> Unit = { println(this is Foo) }

但是,您可以可以声明一个以Foo作为其第一个参数的lambda,并使用这种显式的lambda语法(变量类型仅在此处用于说明目的,否则是多余的,并且会被推断出):

However, you can declare a lambda that takes a Foo as its first parameter, with this explicit lambda syntax (the variable type is only here for explanation purposes, it's otherwise redundant and is inferred):

var foo2: (Foo) -> Unit = { foo: Foo -> println(foo is Foo) }

这两种类型的lambda实际上是可以交叉分配的,因为Foo上的扩展名实际上只是将Foo作为其底层参数.因此,您可以做所有这些事情:

And these two types of lambdas are actually cross-assignable, because the extension on Foo really just takes that Foo as its first parameter under the hood as well. So you can do all of these things:

foo1 = foo2 foo2 = foo1 useFooExtension(foo1) useFooExtension(foo2)

这两种类型之间有一个区别:如果要使用Foo实例调用它们,则只能将foo1作为扩展名调用,但是可以像调用了作为其第一个参数.这些都是有效的呼叫:

There is one difference between the two types: if you want to call them with a Foo instance, you can only call foo1 as an extension, but you can call both of them as if they took a Foo as their first parameter. So these are all valid calls:

Foo().foo1() foo1(Foo()) foo2(Foo())

更多推荐

在lambda文字上指定接收方,而无需类型推断

本文发布于:2023-11-25 17:47:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1630727.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:推断   类型   文字   lambda

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!