Kotlin Tutorial

Kotlin Classes

Array:

Array is a collection data type, and is considered as a container which stores a collection of values. For example an array (container) holding a collection of numbers from 1 to 50.

In Kotlin, Arrays are represented by the Array class. The class got functions like get and set, and also the size property along with some other useful functions.

Create an array using the function arrayOf() and pass the appropriate values to it, like arrayOf(1, 2, 3, 4, 5) creates [1, 2, 3, 4, 5].

To learn more about Arrays, visit: Kotlin Arrays

Type Conversions:

There are several ways to convert one variable type to another. 

If you have a Java background, you may be familiar with how we handle numeric conversions in Java. However, it’s different in Kotlin.

In case of Java:

				
					int num1 = 10;
long num2 = num1; // Correct Code
				
			

Here, num1 int is directly converted into long by assigning num1 variable to num2.

In case of Kotlin:

				
					val num1 : Int = 100
val num2 : Long = num1 // Incorrect Code (Error: Type mismatch)
				
			

Why is this incorrect? Well, though the size of Long is larger than that of Int, so Kotlin doesn’t automatically convert Int to Long.

But Instead you need to do toLong() explicitly to convert type to Long.

Example:

				
					val num1 : Int = 100
val num2 : Long = num1.toLong()
				
			

Kotlin provides built-in functions to convert one type to another.

 

  • toByte()
  • toShort()
  • toInt()
  • toLong()
  • toFloat()
  • toDouble()
  • toChar()


To learn more about Type Casts, visit: Kotlin Type Casts.