Visual Basic 与 Kotlin 中的等效项

Visual Basic With Equivalent in Kotlin

在 Visual Basic 中我们可以使用这样的 With 表达式:

 With theCustomer
        .Name = "Coho Vineyard"
        .URL = "http://www.cohovineyard.com/"
        .City = "Redmond"
 End With

我正在寻找这样的东西。在 Kotlin 中可以吗?

您可以使用 Kotlin 标准库中的 with 函数,例如:

with(theCustomer) {
    name = "Coho Vineyard"
    url = "http://www.cohovineyard.com/"
    city = "Redmond"
}

with() returns 一些结果。它使代码更清晰。

也可以使用apply扩展函数:

theCustomer.apply { 
    name = "Coho Vineyard"
    url = "http://www.cohovineyard.com/"
    city = "Redmond"
}

apply - 在 Any class 上声明,它可以在所有类型的实例上调用,它使代码更具可读性。当需要利用对象的实例(修改属性)时使用,表达调用链。 它与 with() 的不同之处在于它 returns 接收器。

是这样的吗?

    with(theCustomer) {
        Name = "Coho Vineyard"
        URL = "http://www.cohovineyard.com/"
        City = "Redmond"
    }

但是with需要不可为空的参数。我建议改用 letapply

    theCustomer?.apply{
        Name = "Coho Vineyard"
        URL = "http://www.cohovineyard.com/"
        City = "Redmond"
    }

    theCustomer?.let{ customer ->
        customer.Name = "Coho Vineyard"
        customer.URL = "http://www.cohovineyard.com/"
        customer.City = "Redmond"
    }

Kotlin 提供了多个所谓的作用域函数。其中一些使用了 ,这使得编写与您在 Visual Basic 中提供的代码类似的代码成为可能。 withapply 都适用于这种情况。有趣的是 with returns 一些任意结果 Rapply 总是 returns 调用函数的具体接收器。

对于您的示例,让我们考虑这两个函数:

  1. with

    利用with,我们可以这样写代码:

    val customer = Customer()
    with(customer) {
        name = "Coho Vineyard"
        url = "http://www.cohovineyard.com/"
        city = "Redmond"
    } 
    

    此处传递给 with 的 lambda 的最后一个表达式是一个赋值,在 Kotlin 中,它是 returns Unit。您可以将 with 调用的结果分配给某个新变量,该变量将是 Unit 类型。这没有用,整个方法也不是很惯用,因为我们必须将声明与 customer.

  2. 的实际初始化分开
  3. apply

    另一方面,对于 apply,我们可以将声明和初始化结合起来,因为它 returns 默认情况下是它的接收者:

    val customer = Customer().apply {
        name = "Coho Vineyard"
        url = "http://www.cohovineyard.com/"
        city = "Redmond"
    }
    

如您所见,每当您想要初始化某个对象时,首选 apply(在所有类型上定义的扩展函数)。 关于 with 和 apply 之间差异的另一个帖子。