Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I know inferred type in Kotlin?

(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
                       ^
like image 533
letrec Avatar asked Jun 24 '17 04:06

letrec


People also ask

How do I check my Kotlin value type?

Basically, the is operator is used to check the type of the object in Kotlin, and “!is” is the negation of the “is” operator.

How do I know my Kotlin class type?

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) .

What is meant by type inference?

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.

What operator allows you to determine the type of an object in Kotlin?

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.


1 Answers

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.

like image 194
holi-java Avatar answered Oct 20 '22 11:10

holi-java