to
over Pair
syntax KT-C1002The to
function provides better readability and makes the code more self-explanatory. When to
is used, it's more clear
that a pair is being created from two values, improving code comprehension. Furthermore, Kotlin promotes a consistent
and expressive coding style. Using to
aligns with other collection-related functions, such as mapOf
, listOf
, and
setOf
, which also use a similar syntax. This consistency enhances code readability and maintainability.
For example, when creating a map
of strings to integers, one could initialize it like the following:
val map = mapOf(
"ten" to 10,
"twenty" to 20,
)
In the example above, the individual values in the map convey the meaning some value is mapped to some other value. Similarly,
usage of to
in the context of creating a pair conveys the meaning that some value is paired to some other value.
Therefore, it is recommended that you replace the usage of Pair
with to
throughout your codebase.
val pair = Pair(1, 2)
val pair = 1 to 2