# Type Conversion in Kotlin

By | October 9, 2017

Here I write 2  line of code . Both are number but the first number is non fractional number. In kotlin non fraction number built in type is Integer . but you wonder why its not byte , short , long .

this example second line is a fractional number its default data type is double as like other programming language .

If we want to generate a non fractional  data type as ( byte, short, long) we need to convert it explicitly (Explicit casting requires a casting operator. This casting is normally used when converting a `double` to `int` or a base type to a derived type.)

first line we convert a number in byte to write its type . second line we define short and long type variable need to write keyword to define long type variable.

Convert byte (8bit) to Int (32bit)

convert byte type data in integer type no compiler problem arise cause Integer has 32 bit we can easily store 8 bit inside 32 bit no overflow happens.

Convert  Int (32bit) to short (8bit)

this line create compile time error . cause its not possible to store 32 bit element inside a 8 bit element . If you think 32 bit int as a big box and 8 bit byte as a small box. it is possible to store big box inside a small box . that cause this problem aries . How we solve this problem

this is the solution to type casting. this line convert our integer data to byte . Note: this type of operation sometimes losses actual value

this line does not create any problem cause byte store -128 to 127 . so 50 not create any problem . But if we run below code

this code generate wrong answer cause 150 is not possible to store in byte data type .

similer check

• byte to double
• double to byte
• int to double
• double to integer

when you convert fractional data type value to integer it remove fractional part from data . type to write some code and developed your basement of programming . Happy coding