Type conversion in Kotlin vs Java

Type conversion in Kotlin vs Java

In Java, The data type is automatically converted to another data type

but In Kotlin we need to explicitly convert the data type like toInt(), toLong(), toString()

More Type cast methods in Kotlin

toChar() - To convert a data tye to Char type

toInt() - To convert a data type to Int type

toLong() - To convert a data type to Long type

toFloat() - To convert a data type to Float type

toDouble() - To convert a data type to Double type

toByte() - To convert a data type to Byte type

toShort() - To convert a data type to Short type

Example in Java

Int is automatically converted to a Long data type as long is larger than int.


public class Demo {
// Type casting Java
public static void main(String[] args)
{
int a = 10;
long b = a;
System.out.println(a);
System.out.println(b);
}
}


In Kotlin the conversion is not automatic, we need to explicitly do the type conversion.

Example in Kotlin

fun main(args: Array<String>) {
/* Type casting
Java vs Kotlin
*/

val a: Int = 10
val b: Long = a.toLong()
println("a $a b $b")

}

Comments

Popular posts from this blog

Google Assistant Implementation in Android application with app actions