Here is an example:
val a: Int = 6
val b = a.toLong()
val c = a as Long
what is difference between .toLong() and as Long keyword? And what is better way to use
CodePudding user response:
a.toLong()
calls the toLong
method on a
, so it will do whatever the toLong
method does. This method is usually implemented with native code. For example, on the JVM, it can be implemented with the i2l
JVM instruction.
The as
operator on the other hand, does the following, according to the language spec:
This expression perform a runtime check whether the runtime type of
E
is a subtype ofT
and throws an exception otherwise.
So as
only does a check at runtime. The "conversion" happens at compile time only, by means of the language mandating that the type of the expression e as T
must be T
.
As far as Kotlin's type system is concerned, Int
is not a subtype of Long
, so this check will always fail, and this expression will always throw an exception. Note that this is different from Java's type system. where the primitive int
is a subtype of the primitive long
.
CodePudding user response:
Using as
casts that object to that type. It only works when it actually is that type. You'll see that your code actually crashes there where you try to cast the Int
to a Long
. The toLong()
function actually turns it into a Long
.