How to find out the type of output in Kotlin?

(I am using Kotlin 1.1.2-2)

For example, how do I know the output type if (boolean_value) 1 else 2.0 ? kotlinc-jvm does not show type. javaClass also does not help, because it shows the type of the computed value, not the expression.

 >>> (if (true) 1 else 2.0).javaClass.name java.lang.Integer >>> (if (false) 1 else 2.0).javaClass.name java.lang.Double >>> val v: Double = if (false) 1 else 2.0 error: the integer literal does not conform to the expected type Double val v: Double = if (false) 1 else 2.0 ^ 
+5
source share
1 answer

when assigning an if expression with a diff type result to an implicit primitive variable (a variable without a type definition), then the type of the variable is Any / T? or an implicit variable with their direct dinner class P eg:

 // case 1 val v = if (false) 1 else 2.0 // ^--- Any v.toInt(); // error because v is Any // case 2 val v = if (false) 1 else null // ^--- Int? // case 3 val e = if (true) java.sql.Time(1) else java.sql.Timestamp(1); // ^--- its type is java.util.Date 

but you can explicitly define the variable with your superclass, for example:

 // case 1 val v:Number = if (false) 1 else 2.0; v.toInt();//ok // case 2 val v:Int? = if (false) 1 else null; 

Note. You can also use CTRL+SHIFT+P / CTRL+Q to quickly see the type of a variable in IDEA.

+3
source

Source: https://habr.com/ru/post/1269170/


All Articles