Skip to content

Instantly share code, notes, and snippets.

@gaplo917
Last active April 12, 2017 16:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gaplo917/c3b70249b660bff9cdc0b5453c34f98b to your computer and use it in GitHub Desktop.
Save gaplo917/c3b70249b660bff9cdc0b5453c34f98b to your computer and use it in GitHub Desktop.
Type Inference example in Kotlin
// 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!
@ilya-g
Copy link

ilya-g commented Apr 12, 2017

There will be no compiler error in line 7. The type of the resulting map is inferred as Map<String, Any>.

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