Kotlin Variables and Basic Types With Examples – Kotlin Tutorial
1. Overview
In this tutorial, We will learn how to create the variables in Koltin for basic types using var.
var is a keyword in kotlin which is used to
declare the any type of variable.
Kotlin has another keyword ” val” to declare the variables.
Any variable is declared using var that value can be changed at anytime whereas variable declared with val keyword value can not modified one it is initialized.
Mainly val is used to define the constants in kotlin.
2. Variable var examples
var keyword is used in the variable declaration. When you are using var keyword, that indicates the value can be changed at any time and the variable type is optional. If we are not provided the type then it takes the type implicitly based on the value assigned.
Syntax:
var <variable-name> : <variable-type-optional> = value;
Examples:
Below are the few examples on with and without variable type.
First created a double variable with var keyword with 3.14 value. Next used only var and did not mention any type but assigned the value. So it takes it as double internally because value is double type.
Additionally, created a variable with string content and not mentioned its type. But, kotlin has the intelligence to inspect the value and assign the right type.
if you call the welcome.toUpperCase() method, it does not throw any error. because it knows that object is type of String. So, We can use all methods from String class.
package com.javaprogramto.kotlin.variables fun main(args: Array<String>) { // double type var pi : Double = 3.14 println("Double PI value $pi") // without type but it takes the double type internally based on the value var doubleValue = 3.14; println("Default type double $doubleValue") // Without type but it takes as String type from assigned value var welcome = "hello world" println("string welcome note $welcome") var str : String = "i am string" println("string type note $str") }
Output:
Double PI value 3.14 Default type double : doubleValue string welcome note hello world string type note i am string
3. val Variable Examples
val is an another keyword in koltin and it is alos used to declare the variables.
Let us create a variable and try to change the value to new one using var and val variables.
package com.javaprogramto.kotlin.variables fun main(args: Array<String>) { // int type varaible with var keyword var number: Int = 12345; println("old value of number : $number") number = 10000 println("new value of number : $number") // int type variable with val keyword val highestMark: Int = 99; println("old value of highestMark : $number") highestMark = 98 println("new value of highestMark : $number") }
Output:
Kotlin: Val cannot be reassigned
It will produce the compile time error saying value can not be reassigned for val type variable.
So, val keyword is only to declare the constant values because it will not allow to change the value.
4. Difference between var and val
The main difference between the val and var keywords – is var type variables values can be modified and reassigned with the new values but val type variables can not be reassigned with the new values.
5. Assigning the large numbers to variables
When you are using the kotlin in the real time applications, there will be a need to hold the credit card or debit card numbers and phone numbers.
var creditCardNumber : Long = 4320123456782468;
The above number is not readable but it holds the actual value.
To make the numbers more readable, we can use the underscore(_) delimiter in between the numbers.
We can use the underscore for any numbers even it is good to use for currency values or time values.
but when you print or use for different operations, it does not print or get error because of underscore usage. It removes the underscore while performing any mathematical operations. This delimiter just makes the data readable form.
Look the below example for better understanding.
package com.javaprogramto.kotlin.variables fun main(args: Array<String>) { // long numbers with underscore for readable var creditCardNumber: Long = 4320_3456_9808_4389 var debitCardNumber = 1234_45678_1234_9876L var timeInMilliSeconds = 60_000 // printing println("Credit card number : $creditCardNumber") println("Debit card number : $debitCardNumber") println("Time in milli seconds : $timeInMilliSeconds") }
Output:
Credit card number : 4320345698084389 Debit card number : 12344567812349876 Time in milli seconds : 60000
6. Kotlin Variable With Null Values – Null Safe (?)
As of now, we have seen the variable declaration and its initialization in single line. But now you want to do only the declaration with null value.
Now, how can we create a variable with null value in kotlin?
Use the ? symbol at the end of the variable declaration to assign with null value. Look at the below syntax.
val/var <variable-name> : <variable-type-optional> ?;
Sample example program to show variable nullable.
// declaring a variable with the null val noValue : String? // assigning value noValue = "assigned value" // printing the value println("novalue is now : $noValue")
Output:
novalue is now : assigned value
Note: We can not use the null variable without initializing to a value. It show the compile time error “
Kotlin: Variable ‘noValue’ must be initialized“
7. Type Conversions
Next, let us focus on the type conversions in kotlin.
We will try to convert Int to Long value without any casting. Just assign the Int variable to Long variable.
var number1 : Int = 10; var number2 : Long = 12345678; // compile time error : Kotlin: Type mismatch: inferred type is Int but Long was expected // number2 = number1; // right conversion number2 = number1.toLong(); println("number 2 : $number2")
Output:
number 2 : 10
In the above program first directly assigned the int value to the long value but it give compile time error.
Kotlin does not support the direct assignment conversions when the type is mentioned in the declaration. Use toLong() method to do the explicit conversion from Int to Long. This is the process to convert from any type to any type in kotlin.
If the type is not mentioned in the declaration then it is allowed for direct assignment conversion.
var number3 = 10; var number4= 12345678; // no compile time error number4 = number3; println("number4 : $number4")
Output:
number4 : 10
Type conversion with nullable type:
When you are using the nullable value type (?) in the declaration then you must use always the variable usage.
Use the null safe(?) operator when calling methods on the variable otherwise will get the compile time error.
// variable with null type and value assignment var number5 : Int? = 100 var number6 : Long? = 200 // compile time error - Kotlin: Only safe (?.) or non-null asserted (!!.) calls are allowed on a nullable receiver of type Int? // number6 = number5.toLong() // no error with null safe number6 = number5?.toLong(); println("number 6 : $number6")
Output:
number 6 : 100
8. Kotlin Basic Types
Kotlin has the basic type supports as similar to the Java.
- Numbers
Byte
Short
Int
Long
Float
Double
- Char
- Boolean
- Array
Let us explore the different examples on how to create the numbers, characters, booleans and arrays type variables in kotlin.
// Numbers // Byte : range -128 to 127 var byteVar: Byte = 100 println("Byte variable : $byteVar") // Short : range -32768 to 32767 var shortVar: Short = -1000 println("Short variable : $shortVar") // Int : range -2^31 to 2^31-1 var intVar: Int = 12345 println("Int variable : $intVar") // Long : range -2^63 to 2^63-1 var longVar: Long = 12345678900 println("Long variable : $longVar") // Float : single precision 32 bit float point var floatVar: Float = 123.4F // F is mandatory at end else compile time error println("Float variable : $floatVar") // Double : precision 64 bit floating value var doubleVar: Double = 1234.56 println("Double variable : $doubleVar") // Characters // Char var charVar: Char = 'A' println("Char variable : $charVar") // Boolean - this takes only two values - true/false var booleanVar: Boolean = true println("Boolean variable : $booleanVar") var booleanVarFalse: Boolean = false println("Boolean variable false : $booleanVarFalse") // Arrays // implicit type declaration var array1 = listOf(1,2,3,4,5) // explcit type declaration var array2 = listOf<Long>(1,2,3,4,5)
Output:
Byte variable : 100 Short variable : -1000 Int variable : 12345 Long variable : 12345678900 Float variable : 123.4 Double variable : 1234.56 Char variable : A Boolean variable : true Boolean variable false : false
9. Conclusion
In this tutorial, we have seen how declare the variables example programs and other interesting stuff for kotlin programmers.
Published on Java Code Geeks with permission by Venkatesh Nukala, partner at our JCG program. See the original article here: Kotlin Variables and Basic Types With Examples – Kotlin Tutorial Opinions expressed by Java Code Geeks contributors are their own. |