``` val a = 5 val b = 5.4 val c = 5.4321 ```
# getting-started
a
Copy code
val a = 5 
val b = 5.4
val c = 5.4321
c
yes, it is infered when possible
👆 2
s
You can see for yourself with something like this
Copy code
println(a.javaClass.kotlin)
    println(b.javaClass.kotlin)
    println(c.javaClass.kotlin)
k
Might as well go for
a.javaClass.kotlin.java.kotlin
then.
d
Those determine the runtime type, not the static type of the variable at compile time.
s
Ah, I think I misunderstood what he was asking
a
@diesieben07 what's the difference between runtime type and static type?
d
val a: Any = 1
has runtime type
Int
but static type
Any
.
a
So which mean if I define
val a = 1
In runtime it shows
Int
but in static it is
Any
?
d
No, in that case the compiler will infer the type
Int
for
a
, so both static and runtime type will be
Int
. But take this more complicated example:
Copy code
fun iReturnAny(): Any = 3
val a = iReturnAny()
Compiler will infer
Any
for
a
(because
iReturnAny()
returns
Any
), but runtime type will
Int
.
a
Oh.
This is clear.
The static type will assign based on the return type of the function.
However, the runtime type will infer as Int.
d
No. Runtime type is not inferred. Runtime type is the type of the value actually being there at runtime. You can put anything into a variable of type
Any
. The static type will always be
Any
, but the runtime type could be
String
(if there is a string in there) or anything else.
Type inference happens at compile time and it only determines the static (compile time) type of something.
a
Does it matter if the type infer on runtime or static?
d
Again: type inference only happens at compile time.
You can think of type inference as the compiler "typing the obvious for you"
val a = 3
- What type does
a
have? Well, it's an
Int
, "obviously", so let's "type that for you":
val a: Int = 3
That is type inference (basically)
k
You can always check with
Ctrl + Q
on the variable.
âž• 3
a
That's a great tip!