Long Data type Usage and Type Conversion in Kotlin

Definition

  • Long is a 64-bit number in Kotlin The type can be either declared explicitly or the compiler itself has the ability to infer the type of the assigned value.
  • The long data type can have values from -(2^63) to (2^63)-1. Any value less than -(2^31) or greater than (2^31)-1 is inferred automatically by the compiler as a Long value.
  • In JVM, the characteristics of this "Long" variable is derived from the characteristics of primitive type "long" of Java which has a non-nullable default value.

Syntax and declaration

A Long value can be declared by 3 ways as mentioned below.

1. Mentioning type explicitly

val variable_name : Long = value

for example,

val number : Long = 1000

2. Number type is automatically inferred

val variable_name = value

for example,
//Number type is automatically inferred
val number = 1000001234567

3. Declaring and Initializing separately

var variable_name : Long 
variable_name = value

for example

//Declaring and Initializing separately
var number:Long 
number = 10001

Long Datatype Example Program in Kotlin

// Long Datatype Kotlin example program
// Data type Kotlin Programs, Basic Kotlin Programs
	
fun main(args:Array<String>) {
    //Assigning value to Long variable explicitly
    val a:Long = 768
    //Declaring a Long value immediately
    val b:Long = 1000012345677
    
    println("Long value in a is $a")
    println("Long value in b is $b")
}

Sample Output

Long value in a is 768
Long value in b is 1000012345677

Type conversion syntax and declaration

//String to Long Conversion 
val variable_name = "string".toLong()

//Int to Long Conversion 
val variable_name = int_variable.toLong()

Long type Conversion Example Program in Kotlin

// Long Datatype Kotlin example program
// Data type Kotlin Programs, Basic Kotlin Programs

fun main(args: Array < String > ) {
    //Converted from String and Long type is inferred
    val num1 = "1006787676766".toLong()

    //Conversion from String and Declaring an Long value immediately
    val num2: Long = "309878".toLong()

    val num3: Int = 10
    //Conversion from Int
    val num4: Long = num3.toLong()

    val num5: Float = 20.31f
    //Conversion from Float
    val num6: Long = num5.toLong()

    //Print values after conversion
    println("String to Long : num1 Value : $num1")
    println("String to Long : num2 Value : $num2")
    println("Int Value : num3 Value : $num3")
    println("Int to Long : num4 Value : $num4")
    println("Float Value : num5 Value : $num5")
    println("Float to Long : num6 Value : $num6")
}

Sample Output

String to Long : num1 Value : 50
String to Long : num2 Value : 30
Int Value : num3 Value : 10
Int to Long : num4 Value : 10
Float Value : num5 Value : 20.31
Float to Long : num6 Value : 20