Reputation: 89
val (_,time) = time { Thread.sleep(1000) }
I see the Left Hand Side (LHS) has a val, so its declaring a variable. LHS also has some kind of a function syntax which does not look like a lambda declaration. What is (_,time)
? Don’t you have to give a type to the time on the LHS? I understand the RHS perfectly well: it is a function which accepts a lambda as parameter and is named ‘time’. Original code
Upvotes: 4
Views: 919
Reputation: 30528
The left hand side is called destructuring.
If you try to assign an instance of a data class (or any class
which has componentN
functions) to a variable you can desturcture it. This means that you can assign its internals to variables. The _
syntax indicates that you don't care about the first item.
Example:
class Foo(val first: String, val second: String) {
operator fun component1() = first
operator fun component2() = second
}
Usage:
val (first, second) = Foo("first", "second")
If you use data class
es you don't need to create the componentN
functions, they are generated for you.
Equivalent data class
:
data class Foo(val first: String, val second: String)
Upvotes: 7