Kotlin From Scratch: Variables, Basic Types, and Arrays

Kotlin is a modern programming language that compiles to Java bytecode. It is free and open source, and promises to make coding for Android even more fun.

Kotlin is 100% interoperable with Java. In other words, it can be used together with Java in the same project. So you can refactor parts of your Java code to Kotlin and it won’t break. In addition to that, it is concise, expressive, and has great tooling. Kotlin can be used on the back-end (server-side), but it’s getting a lot of attention right now as a language for Android app development. Kotlin is now supported by Google as a first-class language for Android development, so the popularity of Kotlin is set to explode!

In this first tutorial in the Kotlin From Scratch series, you’ll learn about the language basics: comments, variables, simple types, arrays, and type inference.

Prerequisites

To follow along with me, you will need the Kotlin plugin on Android Studio. Alternatively, you could use the online playground or IntelliJ IDEA Community Edition.

Basic Types

In Java, we have two types of type—primitive (e.g. int, long, boolean, byte, char, etc.) and reference types (e.g. array, String). Java uses wrappers (like java.lang.Integer) to make primitive types behave like objects. But in Kotlin, there is no such distinction. Instead, all types are objects.

Numbers

Kotlin supports a variety of number types to store numerical information. Number can either be integers like 20, -17 and 56893 or they can be have a decimal part like 3498.48 or -4.398.

The integer types are subdivided based on the range of their values into four different subtypes. These are:

Type Bits Minimum Value Maximum Value
Long 64 bit -9,223,372,036,854,775,808 9,223,372,036,854,775,807
Int 32 bit -2,147,483,648 2,147,483,647
Short 16 bit -32,768 32,767
Byte 8 bit -128 127

Variables initialized with integer values are assumed to have type Int by the compiler if you haven’t explicitly specified a type and the value itself is within the limits of Int type. Variables with larger initialization values are assumed to be Long.

The real number or floating-point types are:

Type Bits Mantissa Bits Exponent Bits
Double 64 bits 53 bits 11 bits
Float 32 bits 24 bits 8 bits

You can observe that we created a Long literal by adding the suffix L, and for Float we added the suffix F or f. Numbers can also be written in hexadecimal notation using the 0x or 0X prefix and in binary using the 0b or 0B prefix. Note that in all these cases, Kotlin can use type inference to know the type we want instead.

To convert a number from one type to another, you have to explicitly invoke the corresponding conversion function. In other words, there is no implicit conversion between types of numbers.

Each number type has helper functions that convert from one number type to another: toByte(), toInt(), toLong(), toFloat(), toDouble(), toChar(), toShort().

In the code above, we are converting from an integer to a long. We can also do the reverse by using the method toInt() on the long variable. Note that this will truncate the value to fit the smaller size of an Int type if need be — so be careful when converting from larger types to smaller ones!

You can also convert a String into a number type.

In the code above, we converted the variable stringNumber into an Int type by calling the method toInt() on the variable. We can write this more succinctly by instead calling the method directly on the string:

One more thing that I would like to mention is that arithmetic operations on small number types such Byte and Short return an Int. This can give you some unexpected compiler errors. You will have to cast the result to a Byte type even if the variable was already a Byte. Here is an example:

The Boolean Type

The Boolean type in Kotlin is the same as in Java. Its value can be either true or false. The operations disjunction (||), conjunction (&&), and negation (!) can be performed on boolean types, just like Java.

Strings

Strings can be created with either double quotes or triple quotes. In addition to that, escape characters can be used with double quotes.

To create a string that spans multiple lines in the source file, we use triple quotes:

Kotlin also supports string interpolation or string templates. This is an easier way to build dynamic strings than concatenation, which is what we use in Java. Using string templates, we can insert variables and expressions into a string.

In the code above, we created a string literal, and inside it, we referred to a variable by the use of a $ character in front of the variable name. Note that if the variable is not correct or doesn’t exist, the code won’t compile.

What about if you need to use $ in your string? You just escape it with \$! Also, you can call methods from an interpolated String directly. You just have to add curly braces ${} to wrap it.

Another cool thing you can do is to perform some logic inside the curly braces when creating a String literal.

When working with strings, remember that any operation on a string that can transform its value will result in creation of new String object. The original string will remain unchanged. Here is an example:

Arrays

In Kotlin, there are two main ways to create an array: using the helper function arrayOf() or the constructor Array().

The arrayOf() Function

For example, let’s create an array with some elements using arrayOf().

Now, to access any of the element, we can use its index: myArray[2]. Note that we can pass in values of different types into the arrayOf() as arguments and it will still work—it will be an array of mixed type.

To enforce that all the array values have the same type, e.g. Int, we declare a type by calling arrayOf<Int>() or intArrayOf().

We also have other utility functions to create arrays of other types such as charArrayOf(), booleanArrayOf(), longArrayOf(), shortArrayOf(), byteArrayOf(), and so on. Behind the scenes, using these functions will create an array of their respective Java primitive types. In other words, intArrayOf() will compile to the regular Java primitive type int[], byteArrayOf() will be byte[], longArrayOf() will be long[], and so on.

The Array() Constructor

Now let’s see how to create an array with Array(). The constructor of this class requires a size and a lambda function. We’ll learn more about lambda functions later in this series, but for now, just understand that it is a simple, inline way of declaring an anonymous function. In this case, the job of the lambda function is to initialize the array with elements.

In the code above, we have used slightly different syntax to initialize our arrays. In both cases, we passed 5 as the size of the array in the first argument. The second argument takes in a lambda function, which takes the index of the array element and then returns the value to be inserted at that index in the array. So in the example above, the end result was creation of two arrays with first five odd and even values.

You can also use more specific classes to create arrays which contain elements of specific types. For example, IntArray will create an array of Int type. Trying to include any other type of value into the array will result in error.

When we only passed the size of IntArray, all the values were initialized to 0. Passing 5 as an additional value initialized all elements to 5. Trying to pass a string value into an IntArray will throw an error. Similar classes also exist for other number types.

Variables

During our discussion on types, you might have noticed that we were using keywords like val and var. In Kotlin, use val to declare an immutable variable and var to declare a mutable variable. You can also optionally specify a type such as String or Int after the variable name. In the example below, we declared a constant firstName of type String with the val keyword.

But you’ll soon realize that in Kotlin, it’s often possible to omit the type from the declaration and the compiler won’t complain.

In the code above, you’ll observe that we did not explicitly state the type String. The code above will still work because the compiler has implicitly inferred the type using type inference. We’ll come back to this!

The difference between the val and var keywords is that the former is immutable or read-only (its value cannot be changed), while the latter is mutable (its value can be changed).

Note that for a variable declared with the var keyword which has its type inferred by the compiler, assigning another value of a different type won’t work. In other words, the value of the variable can change, but its type cannot! For example:

It is highly recommended that you start by making your variables immutable by declaring them with the val keyword, so as not to maintain too many states. This makes your code safer for multithreading, because it ensures your variables cannot be modified by other threads unexpectedly.

Another thing you should know about the val keyword is that you can declare it with a type only and assign it a value later. But you can still only assign a value once.

However, you should keep in mind that using val only prevents reassignment. It doesn’t prevent people from making any other kind of changes as shown below.

In Java, it’s possible to declare multiple variables of the same type on a single line, but this doesn’t work in Kotlin. In Kotlin, all variable declarations must be on their own lines.

Type Inference or Deduction

Kotlin is a strongly typed language that supports type inference or deduction. This is the mechanism employed by the compiler to find out types from context. Java doesn’t have a type inference mechanism, which means you must explicitly declare the type of every function or variable. Type inference helps reduce the boilerplate code you have to write.

The code above would compile even though we did not explicitly state the type for the variable country. The compiler is smart enough to know that the country is of type String, because the value, “Nigeria”, is a string.

Comments

This is an easy one. In Kotlin, comments are just the same as in Java. We can use either block or line comments:

Conclusion

In this tutorial, you learned the basics of the Kotlin programming language: variables, basic types, type inference, arrays, and comments. In the next tutorial in the Kotlin From Scratch series, you’ll learn about loops, ranges, conditions, collections, and packages in Kotlin. See you soon!

To learn more about the Kotlin language, I recommend visiting the Kotlin documentation. Or check out some of our other Kotlin tutorials here on Envato Tuts+.

This post has been updated with contributions from Nitish Kumar. Nitish is a web developer with experience in creating eCommerce websites on various platforms. He spends his free time time working on personal projects that make his everyday life easier or taking long evening walks with friends.


This content originally appeared on Envato Tuts+ Tutorials and was authored by Chike Mgbemena

Kotlin is a modern programming language that compiles to Java bytecode. It is free and open source, and promises to make coding for Android even more fun.

Kotlin is 100% interoperable with Java. In other words, it can be used together with Java in the same project. So you can refactor parts of your Java code to Kotlin and it won't break. In addition to that, it is concise, expressive, and has great tooling. Kotlin can be used on the back-end (server-side), but it's getting a lot of attention right now as a language for Android app development. Kotlin is now supported by Google as a first-class language for Android development, so the popularity of Kotlin is set to explode!

In this first tutorial in the Kotlin From Scratch series, you'll learn about the language basics: comments, variables, simple types, arrays, and type inference.

Prerequisites

To follow along with me, you will need the Kotlin plugin on Android Studio. Alternatively, you could use the online playground or IntelliJ IDEA Community Edition.

Basic Types

In Java, we have two types of type—primitive (e.g. int, long, boolean, byte, char, etc.) and reference types (e.g. array, String). Java uses wrappers (like java.lang.Integer) to make primitive types behave like objects. But in Kotlin, there is no such distinction. Instead, all types are objects.

Numbers

Kotlin supports a variety of number types to store numerical information. Number can either be integers like 20, -17 and 56893 or they can be have a decimal part like 3498.48 or -4.398.

The integer types are subdivided based on the range of their values into four different subtypes. These are:

Type Bits Minimum Value Maximum Value
Long 64 bit -9,223,372,036,854,775,808 9,223,372,036,854,775,807
Int 32 bit -2,147,483,648 2,147,483,647
Short 16 bit -32,768 32,767
Byte 8 bit -128 127

Variables initialized with integer values are assumed to have type Int by the compiler if you haven't explicitly specified a type and the value itself is within the limits of Int type. Variables with larger initialization values are assumed to be Long.

The real number or floating-point types are:

Type Bits Mantissa Bits Exponent Bits
Double 64 bits 53 bits 11 bits
Float 32 bits 24 bits 8 bits

You can observe that we created a Long literal by adding the suffix L, and for Float we added the suffix F or f. Numbers can also be written in hexadecimal notation using the 0x or 0X prefix and in binary using the 0b or 0B prefix. Note that in all these cases, Kotlin can use type inference to know the type we want instead.

To convert a number from one type to another, you have to explicitly invoke the corresponding conversion function. In other words, there is no implicit conversion between types of numbers.

Each number type has helper functions that convert from one number type to another: toByte(), toInt(), toLong(), toFloat(), toDouble(), toChar(), toShort().

In the code above, we are converting from an integer to a long. We can also do the reverse by using the method toInt() on the long variable. Note that this will truncate the value to fit the smaller size of an Int type if need be — so be careful when converting from larger types to smaller ones!

You can also convert a String into a number type.

In the code above, we converted the variable stringNumber into an Int type by calling the method toInt() on the variable. We can write this more succinctly by instead calling the method directly on the string:

One more thing that I would like to mention is that arithmetic operations on small number types such Byte and Short return an Int. This can give you some unexpected compiler errors. You will have to cast the result to a Byte type even if the variable was already a Byte. Here is an example:

The Boolean Type

The Boolean type in Kotlin is the same as in Java. Its value can be either true or false. The operations disjunction (||), conjunction (&&), and negation (!) can be performed on boolean types, just like Java.

Strings

Strings can be created with either double quotes or triple quotes. In addition to that, escape characters can be used with double quotes.

To create a string that spans multiple lines in the source file, we use triple quotes:

Kotlin also supports string interpolation or string templates. This is an easier way to build dynamic strings than concatenation, which is what we use in Java. Using string templates, we can insert variables and expressions into a string.

In the code above, we created a string literal, and inside it, we referred to a variable by the use of a $ character in front of the variable name. Note that if the variable is not correct or doesn't exist, the code won't compile.

What about if you need to use $ in your string? You just escape it with \$! Also, you can call methods from an interpolated String directly. You just have to add curly braces ${} to wrap it.

Another cool thing you can do is to perform some logic inside the curly braces when creating a String literal.

When working with strings, remember that any operation on a string that can transform its value will result in creation of new String object. The original string will remain unchanged. Here is an example:

Arrays

In Kotlin, there are two main ways to create an array: using the helper function arrayOf() or the constructor Array().

The arrayOf() Function

For example, let's create an array with some elements using arrayOf().

Now, to access any of the element, we can use its index: myArray[2]. Note that we can pass in values of different types into the arrayOf() as arguments and it will still work—it will be an array of mixed type.

To enforce that all the array values have the same type, e.g. Int, we declare a type by calling arrayOf<Int>() or intArrayOf().

We also have other utility functions to create arrays of other types such as charArrayOf(), booleanArrayOf(), longArrayOf(), shortArrayOf(), byteArrayOf(), and so on. Behind the scenes, using these functions will create an array of their respective Java primitive types. In other words, intArrayOf() will compile to the regular Java primitive type int[], byteArrayOf() will be byte[], longArrayOf() will be long[], and so on.

The Array() Constructor

Now let's see how to create an array with Array(). The constructor of this class requires a size and a lambda function. We'll learn more about lambda functions later in this series, but for now, just understand that it is a simple, inline way of declaring an anonymous function. In this case, the job of the lambda function is to initialize the array with elements.

In the code above, we have used slightly different syntax to initialize our arrays. In both cases, we passed 5 as the size of the array in the first argument. The second argument takes in a lambda function, which takes the index of the array element and then returns the value to be inserted at that index in the array. So in the example above, the end result was creation of two arrays with first five odd and even values.

You can also use more specific classes to create arrays which contain elements of specific types. For example, IntArray will create an array of Int type. Trying to include any other type of value into the array will result in error.

When we only passed the size of IntArray, all the values were initialized to 0. Passing 5 as an additional value initialized all elements to 5. Trying to pass a string value into an IntArray will throw an error. Similar classes also exist for other number types.

Variables

During our discussion on types, you might have noticed that we were using keywords like val and var. In Kotlin, use val to declare an immutable variable and var to declare a mutable variable. You can also optionally specify a type such as String or Int after the variable name. In the example below, we declared a constant firstName of type String with the val keyword.

But you'll soon realize that in Kotlin, it's often possible to omit the type from the declaration and the compiler won't complain.

In the code above, you'll observe that we did not explicitly state the type String. The code above will still work because the compiler has implicitly inferred the type using type inference. We'll come back to this!

The difference between the val and var keywords is that the former is immutable or read-only (its value cannot be changed), while the latter is mutable (its value can be changed).

Note that for a variable declared with the var keyword which has its type inferred by the compiler, assigning another value of a different type won't work. In other words, the value of the variable can change, but its type cannot! For example:

It is highly recommended that you start by making your variables immutable by declaring them with the val keyword, so as not to maintain too many states. This makes your code safer for multithreading, because it ensures your variables cannot be modified by other threads unexpectedly.

Another thing you should know about the val keyword is that you can declare it with a type only and assign it a value later. But you can still only assign a value once.

However, you should keep in mind that using val only prevents reassignment. It doesn't prevent people from making any other kind of changes as shown below.

In Java, it's possible to declare multiple variables of the same type on a single line, but this doesn't work in Kotlin. In Kotlin, all variable declarations must be on their own lines.

Type Inference or Deduction

Kotlin is a strongly typed language that supports type inference or deduction. This is the mechanism employed by the compiler to find out types from context. Java doesn't have a type inference mechanism, which means you must explicitly declare the type of every function or variable. Type inference helps reduce the boilerplate code you have to write.

The code above would compile even though we did not explicitly state the type for the variable country. The compiler is smart enough to know that the country is of type String, because the value, "Nigeria", is a string.

Comments

This is an easy one. In Kotlin, comments are just the same as in Java. We can use either block or line comments:

Conclusion

In this tutorial, you learned the basics of the Kotlin programming language: variables, basic types, type inference, arrays, and comments. In the next tutorial in the Kotlin From Scratch series, you'll learn about loops, ranges, conditions, collections, and packages in Kotlin. See you soon!

To learn more about the Kotlin language, I recommend visiting the Kotlin documentation. Or check out some of our other Kotlin tutorials here on Envato Tuts+.

This post has been updated with contributions from Nitish Kumar. Nitish is a web developer with experience in creating eCommerce websites on various platforms. He spends his free time time working on personal projects that make his everyday life easier or taking long evening walks with friends.


This content originally appeared on Envato Tuts+ Tutorials and was authored by Chike Mgbemena


Print Share Comment Cite Upload Translate Updates
APA

Chike Mgbemena | Sciencx (2017-08-04T06:36:13+00:00) Kotlin From Scratch: Variables, Basic Types, and Arrays. Retrieved from https://www.scien.cx/2017/08/04/kotlin-from-scratch-variables-basic-types-and-arrays/

MLA
" » Kotlin From Scratch: Variables, Basic Types, and Arrays." Chike Mgbemena | Sciencx - Friday August 4, 2017, https://www.scien.cx/2017/08/04/kotlin-from-scratch-variables-basic-types-and-arrays/
HARVARD
Chike Mgbemena | Sciencx Friday August 4, 2017 » Kotlin From Scratch: Variables, Basic Types, and Arrays., viewed ,<https://www.scien.cx/2017/08/04/kotlin-from-scratch-variables-basic-types-and-arrays/>
VANCOUVER
Chike Mgbemena | Sciencx - » Kotlin From Scratch: Variables, Basic Types, and Arrays. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2017/08/04/kotlin-from-scratch-variables-basic-types-and-arrays/
CHICAGO
" » Kotlin From Scratch: Variables, Basic Types, and Arrays." Chike Mgbemena | Sciencx - Accessed . https://www.scien.cx/2017/08/04/kotlin-from-scratch-variables-basic-types-and-arrays/
IEEE
" » Kotlin From Scratch: Variables, Basic Types, and Arrays." Chike Mgbemena | Sciencx [Online]. Available: https://www.scien.cx/2017/08/04/kotlin-from-scratch-variables-basic-types-and-arrays/. [Accessed: ]
rf:citation
» Kotlin From Scratch: Variables, Basic Types, and Arrays | Chike Mgbemena | Sciencx | https://www.scien.cx/2017/08/04/kotlin-from-scratch-variables-basic-types-and-arrays/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.