(I use Kotlin 1.1.2-2)
For example, how do I know the inferred type of expression if (boolean_value) 1 else 2.0
? kotlinc-jvm
doesn't show the type. javaClass
also doesn't help because it shows the type of computed value not 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
^
Basically, the is operator is used to check the type of the object in Kotlin, and “!is” is the negation of the “is” operator.
Type check is a way of checking the type( DataType ) or Class of a particular instance or variable while runtime to separate the flow for different objects. In few languages, it's also denoted as Run Time Type Identification (RTTI) .
Type inference refers to the automatic detection of the type of an expression in a formal language. These include programming languages and mathematical type systems, but also natural languages in some branches of computer science and linguistics.
In Kotlin, You can check whether an object is of a certain type at runtime by using the is operator. Following is an example that demonstrates the usage of is operator. In the example above, We have a list containing mixed types.
when assign the if expression with diff type result to an implicit primitive variable (variable without type definition) then the variable type is Any
/T?
, or an implicit variable with their direct supper class P
. for example:
// 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 define the variable explicitly with their 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 using CTRL+SHIFT+P
/CTRL+Q
to see the variable type quickly in IDEA.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With