natario1
10/27/2020, 12:14 PMfun getMarkerLocation(): Pair<Double, Double> { ... }
fun addMarker(name: String, lat: Double, lng: Double, color: Int) { ... }
addMarker(
name = "marker",
color = Color.RED,
(lat, lng) = getMarkerLocation()
)
I wonder if this has ever been discussed.Nir
10/29/2020, 6:56 PMnatario1
10/29/2020, 7:16 PMfun getDefaultMarkerLocation(): Pair<Double, Double> { }
class Marker(val lat: Double, val lng: Double) {
constructor() : this((lat, lng) = getDefaultMarkerLocation())
}
Currently the only way to do have this is to add another constructor or use a factory function instead.Nir
10/29/2020, 7:19 PMNir
10/29/2020, 7:19 PMNir
10/29/2020, 7:20 PMnatario1
10/29/2020, 7:21 PMNir
10/29/2020, 7:21 PMNir
10/29/2020, 7:21 PMgildor
10/31/2020, 2:41 AMnatario1
10/31/2020, 12:48 PMgildor
10/31/2020, 12:56 PMleverage a very familiar syntaxThat is a problem, that this syntax already used for destructuring, but for position destructuring, not named one, so they have different behavior depending on call context
natario1
10/31/2020, 1:00 PMcomponentX()
functions as always.gildor
10/31/2020, 1:05 PMgildor
10/31/2020, 1:07 PMnatario1
10/31/2020, 1:11 PM(lng, lat) = getMarkers()
would be equally wrong in a val
assignment than it would be in a function call with named params. We're not introducing any new errorgildor
10/31/2020, 3:34 PMnatario1
10/31/2020, 4:39 PMdata class Location(val lat: Double, val lng: Double)
data class LocationSwapped(val LNG: Double, val LAT: Double)
val location: Location = getLocation() // whatever
val locationSwapped = LocationSwapped((LAT, LNG) = location)
assertEquals(location.lat == locationSwapped.LAT)
assertEquals(location.lng == locationSwapped.LNG)
And it would work fine, because LAT
and LNG
names in the destructuring operation match the names of the LocationSwapped
constructor.
You wouldn't be allowed to use a different name that does not match any argument, I can't call LocationSwapped((XXX, YYY) = location) because the constructor does not have XXX and YYY parameters. It only has LAT and LNG.
So in this example LocationSwapped
is created with named parameters , while Location
is destructured positionally, as always. Just like calling LocationSwapped(LAT = location.component1(), LNG = location.component2())