在lambda文字上指定接收方,而无需类型推断 [英] Specify receiver on lambda literal without type inference

查看:78
本文介绍了在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文字上指定接收方,而无需类型推断的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆