Last active
April 12, 2017 16:11
-
-
Save gaplo917/c3b70249b660bff9cdc0b5453c34f98b to your computer and use it in GitHub Desktop.
Type Inference example in Kotlin
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// val abc: Map<String,Int> = mapOf("a" to 1, "b" to 2, "c" to 3) | |
// the actual type of the Map is obvious | |
// thus we can skip Map<String,Int> and let kotlin compiler to make type inference | |
val abc = mapOf("a" to 1, "b" to 2, "c" to 3) | |
val abcd = abc + ("d" to 4) // ok! | |
val abce = abc + ("e" to "5") // compile error: Type mismatch | |
// val c: Int? = abc["c"] | |
var c = abc["c"] | |
c = "2" // compile error: Type mismatch | |
// Same Question: | |
// If you are asked to refactor from Map<String,Integer> to Map<String,String>, | |
// try to estimate the efforts! |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
There will be no compiler error in line 7. The type of the resulting map is inferred as
Map<String, Any>
.