Skip to content

Instantly share code, notes, and snippets.

@harsh183
Last active April 23, 2021 12:53
Show Gist options
  • Save harsh183/0b37207cd79b93037b9d30ca665414d4 to your computer and use it in GitHub Desktop.
Save harsh183/0b37207cd79b93037b9d30ca665414d4 to your computer and use it in GitHub Desktop.
Comparing directly declaring lists vs initializer functions (using lambdas). The syntax is pretty decent except for maps but to be fair if you're doing this type of thing you should not be using maps.
fun main() {
// Both are the same
val array1: Array<Int> = arrayOf(0, 1, 4, 9, 16)
val list1: List<Int> = listOf(0, 1, 4, 9, 16)
val map1: Map<Int, Int> = mapOf(0 to 0, 1 to 1, 2 to 4, 3 to 9, 4 to 16)
val array2: Array<Int> = Array(5) { it*it }
val list2: List<Int> = List(5) {it*it}
val map2: Map<Int, Int> = (Array(5) {it}).associate {it to it*it}
}
@harsh183
Copy link
Author

harsh183 commented Jan 15, 2020

Note: Kotlin type inference is so good this entire code works without Type declarations.

    val array1 = arrayOf(0, 1, 4, 9, 16)
    val list1 = listOf(0, 1, 4, 9, 16)
    val map1 = mapOf(0 to 0, 1 to 1, 2 to 4, 3 to 9, 4 to 16)
    
    val array2 = Array(5) { it*it }
    val list2= List(5) {it*it}
    val map2 = (Array(5) {it}).associate {it to it*it}

@harsh183
Copy link
Author

MIT License

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment