kotlinbasic

Visual Basic With Equivalent in Kotlin


In Visual Basic we can use With Expression like this:

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

I'm looking for something like this. Is it possible in Kotlin?


Solution

  • Kotlin provides multiple, so called, scope functions. Some of them make use of a function literal with receiver, which make it possible to write similar code as provided by you in Visual Basic. Both, with and apply are suitable for this case. It's interesting to note that with returns some arbitrary result R while apply always returns the concrete receiver on which the function has been invoked.

    For your example, let's consider both functions:

    1. with

      Using with, we can write the code as follows:

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

      The last expression of the lambda passed to with here is an assignment, which, in Kotlin, returns Unit. You could assign the result of the with call to some new variable which would then be of type Unit. This is not useful and the whole approach is not very idiomatic since we have to separate the declaration from the actual initialization of customer.

    2. apply

      With apply on the other hand, we can combine declaration and initialization as it returns its receiver by default:

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

    As you can see, whenever you want to initialize some object, prefer apply (extension function defined on all types). Here's another thread on the differences between with and apply.