Kotlin中的“with”是什么意思?
我已经阅读了3次文档,但我仍然不知道它的功能。 有人可以ELI5(请解释我是五)吗? 以下是我如何使用它:
fun main(args: Array<String>) { val UserModel = UserModel() val app = Javalin.create().port(7000).start() with (app) { get("/users") { context -> context.json(UserModel) } } }
该文件说:
inline fun <T, R> with(receiver: T, block: T.() -> R): R (source)
用给定的接收器作为接收器调用指定的功能块并返回结果。
我想到的方式是调用一个函数( block
),在block
的范围内是receiver
。 无论返回类型是什么block
返回。
调用一个提供隐式的方法,并可以返回任何结果。
举一个例子可能会更容易一些:
val rec = "hello" val returnedValue: Int = with(rec) { println("$this is ${length}") lastIndexOf("l") }
在这种情况下rec
是函数调用的接收者 – this
在block
的范围内。 $length
和lastIndexOf
都在接收器上调用。
返回值可以看作是一个Int
因为这是body
的最后一个方法调用 – 也就是签名的泛型类型参数R
with
的定义:
inline fun <T, R> with(receiver: T, block: T.() -> R): R (source)
实际上它的实现很简单: block
在receiver
上执行,适用于任何类型:
receiver.block() //that's the body of `with`
在这里提到的伟大的事情是参数类型T.() -> R
:它被称为与接收器的函数文字 。 它实际上是一个lambda ,可以访问接收者的成员没有任何额外的限定符。
在你的例子中with
接收者app
的context
是以这种方式访问的。
除了像with
或apply
stdlib函数之外,这个功能还是Kotlin编写域特定语言的好工具,因为它允许创建在某些功能上可以访问的范围。
with
用于访问对象的成员和方法,而不必在每次访问时都引用该对象。 它(大部分)是缩写你的代码。 构建对象时经常使用它:
// Verbose way, 219 characters: var thing = Thingummy() thing.component1 = something() thing.component2 = somethingElse() thing.component3 = constantValue thing.component4 = foo() thing.component5 = bar() parent.children.add(thing) thing.refcount = 1 // Terse way, 205 characters: var thing = with(Thingummy()) { component1 = something() component2 = somethingElse() component3 = constantValue component4 = foo() component5 = bar() parent.children.add(this) refcount = 1 }