How to get the compiler to say what type it thinks an expression is?

Viewed 67

Is there a way to get the Kotlin compiler to tell me exactly what type it thinks an expression is? So e.g. given (1 + 2) it would print Int.

Better example: (if (args.isEmpty()) 1 else 2.0) should print Any, because that's what the compiler thinks is the type of that term, because the best it can do at compile time is infer the most specific supertype of Int and Double.

2 Answers
fun main() {
    println(typeName { if (true) 1 else 2.5 }) // Any
    println(typeName { 1 + 2 }) // Int
    println(typeName { f() }) // String
}


fun f(): String = TODO() // throws NotImplementedError

inline fun <reified T> typeName(block: () -> T): String? = T::class.simpleName

If you need this functionality while you're editing your code, IntelliJ based IDEs support this. The action is called Type Info, and you can access it with Ctrl + Shift + P (⌃⇧P on macOS) by default.

Example of using Type Info

Related