Kotlin — Overview and Basic Types
In a recent DiscoverSDK article, we reported on the fastest growing programming languages as we kick off 2019. The rankings were based on the growth in the number of contributors as reported by GitHub and Kotlin was the number one fastest growing. It’s not really much of a surprise as it greatly improves upon Java. That means the countless Java developers out there can make the switch to a new language that’s a real pleasure to work with. Oh, and it’s a first-class citizen in Android.
Kotlin is designed to be a newer, better Java. It is a high level, strongly and statically typed language. It’s designed to interoperate fully with Java, and the JVM version of its standard library depends on the Java Class Library. While not identical, Kotlin’s syntax will feel like home for Java programmers while providing interoperability and code safety.
Pros and Cons
Here are a few pros and cons for using Kotlin in your next development project.
Pros:
Learning Curve: Kotlin is a functional language and is quite easy to learn. The syntax is similar to Java so for Java developers, it’ll take no time at all. Kotlin greatly improves upon readability when compared to Java.
Concise: Kotlin is a functional language and is based on JVM. It is much less verbose than Java and you’ll need far less boilerplate code.
Runtime and Performance: It offers better performance and a smaller runtime than Java.
Interoperability: Kotlin allows you to build an interoperable application in a straightforward manner.
Cons:
Namespace declaration: Kotlin lets developers declare functions at the top level. The problem is, whenever the same function is declared in several places in the application, it can become difficult to understand which function is being called.
No Static Declaration: Kotlin does not have normal static handling modifiers like Java. This may cause some problems for some Java developers.
In this article, and in future Kotlin articles, we’ll be using code examples that you can run in any Kotlin environment. If you don’t feel like setting up a local environment, there are several places online where you can run Kotlin. We suggest this one from Kotlin itself.
If you do want to set up a local Kotlin environment you have several options. You’ll need to make sure you have Java installed and then you’ll need an IDE like NetBeans, Eclipse, or IntelliJ Idea. Whether you’ve set up your local environment, or just want to try things out online, your first Kolin ‘Hello World’ program should look like this:
fun main(args: Array<String>) {
println("Hello World!")
}
And your output to the console will be:
Hello World!
Pretty exciting indeed.
Architecture
Kotlin has its own architecture for the allocation of memory and produces quality output for the end user. There are various scenarios where the Kotlin compiler will work differently depending upon which language it’s targeting, such as Java or JavaScript.
The Kotlin compiler creates byte code which can run on the JVM. This equals exactly the byte code generated by the Java .class file. Any time two byte code files run on the JVM, they are able to communicate with each other which is how the interoperable feature is established in Kotlin for Java.
Whenever Kotlin targets JavaScript, the Kotlin compiler converts the .kt file into ES5.1 and then generates code for JavaScript. The Kotlin compiler is capable of creating platform basis compatible code via the LLVM compiler infrastructure project.
Basic Data Types in Kotlin
Now, let’s examine some of the basic data types in Kotlin.
Numbers
Numbers are represented in Kotlin in a similar manner to Java. However, Kotlin does not allow for the internal conversion of different data types. The following table shows the different variable lengths for different numbers.
Type |
Size |
Double |
64 |
Long |
64 |
Float |
32 |
Int |
32 |
Short |
16 |
Byte |
8 |
Have a look at the following code snippet to see how Kotlin works with different data types. Run the code and see the result.
fun main(args: Array<String>) {
val a: Int = 10000
val f: Float = 100.00f
val d: Double = 100.00
val l: Long = 1000000004
val s: Short = 10
val b: Byte = 1
println("The Int Value is "+a);
println("The Float Value is "+f);
println("The Double Value is "+d);
println("The Long Value is "+l);
println("The Short Value is "+s);
println("The Byte Value is "+b);
}
Here’s what you should see in the console:
The Int Value is 10000
The Float Value is 100.0
The Double Value is 100.0
The Long Value is 1000000004
The Short Value is 10
The Byte Value is 1
Characters
In Kotlin, characters are represented using char. Best practice is to declared characters in a single quote as in ‘x’. To see how Kotlin interprets a character variable, run the code below in the Kotlin playground, or in your local environment. You cannot declare character variables as you would number variables. Kotlin variables can be declared in one of two ways: using var or using val.
fun main(args: Array<String>) {
val letter: Char // define a variable
letter = 'X' // Assigne a value to that variable
println("$letter")
}
This code will give you the following output.
X
Boolean
Booleans in Kotlin are straightforward, just like in most other programming languages. A boolean can return only one of two values: true or false. In the code below, you can see how Kotlin interprets a boolean.
fun main(args: Array<String>) {
val letter: Boolean // define the variable
letter = true // Assigne a value to that variable
println("The value of your character is "+"$letter")
}
This code will return the following output:
The value of your character is true
Strings
Strings are a sequence of characters. In Kotlin, all strings are objects of the class String. Just as in Java, Kotlin strings are immutable. There are two types of strings at our disposal in Kotlin: one is the raw string and another is known as an escaped string. Let’s have a look at how both of these strings function:
fun main(args: Array<String>) {
var rawString :String = "I am a raw string!"
val escapedString : String = "I am an escaped string!\n"
println("Greetings! "+escapedString)
println("Salutations! "+rawString)
}
The example of the escaped string allows to for an extra line space after the first print statement. This is how the output will appear.
Greetings! I am an escaped string!
Salutations! I am a raw string!
Arrays
An array is a collection of a set number of values and is represented by the class Array. Just as in Java, Kotlin supports arrays of different data types. Here is an example where we’ll try out a few different arrays. Items in Kotlin arrays are referred to as elements.
fun main(args: Array<String>) {
val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)
println("Hello, I am an example of an array "+numbers[2])
}
Here is the output from this code example. The array indexing in Kotlin is similar to that of other programming languages. Notice that we are searching for a second index, whose value is “3”.
Hello, I am an example of an array 3
Collections
Collections are an important part of the data structure, helping to make software development easier for engineers. There are two types of collections in Kotlin: immutable (such as lists, maps, and sets that cannot be edited) and mutable (a type of collection that can be edited). It is important to keep in mind the type of collection you are using in your application since Kotlin does not show any particular difference between them.
fun main(args: Array<String>) {
val numbers: MutableList<Int> = mutableListOf(1, 2, 3) //a mutable List
val readOnlyView: List<Int> = numbers //an immutable list
println("a mutable list--"+numbers) // prints "[1, 2, 3]"
numbers.add(4)
println("a mutable list after addition --"+numbers) // prints "[1, 2, 3, 4]"
println(readOnlyView)
readOnlyView.clear() // ⇒ does not compile
// gives error
}
This block of code actually gives us an error when we try to clear the mutable list of collection.
Error:(8, 16) Unresolved reference. None of the following candidates is applicable because of receiver type mismatch:
@SinceKotlin public fun kotlin.text.StringBuilder /* = java.lang.StringBuilder */.clear(): kotlin.text.StringBuilder /* = java.lang.StringBuilder */ defined in kotlin.text
With collections, Kotlin gives us some useful methods like first(), last(), filter(), and more. All of these methods are self-explanatory and easy to implement. Further, Kotlin uses the same structure such as Java when implementing collections. You are free to implement any collection of you want like Map or Set.
In this example, we have implemented Map and Set using a few different built-in methods.
fun main(args: Array<String>) {
val items = listOf(1, 2, 3, 4)
println("The first Element in our list----"+items.first())
println("The last Element in our list----"+items.last())
println("Even Numbers in our List----"+items.
filter { it % 2 == 0 }) // returns [2, 4]
val readWriteMap = hashMapOf("foo" to 1, "bar" to 2)
println(readWriteMap["foo"]) // prints "1"
val strings = hashSetOf("a", "b", "c", "c")
println("The Set Values are as follows: "+strings)
}
Here is the output you should receive:
The first Element in our list----1
The last Element in our list----4
Even Numbers in our List----[2, 4]
1
The Set Values are as follows: [a, b, c]
Ranges
Ranges are another unique feature of Kotlin. Like in Haskell, ranges give you an operator allowing you to iterate through a range. Internally, it is implemented using rangeTo() and its operator form is (..).
Let’s look at how Kotlin interprets the range operator:
fun main(args: Array<String>) {
val i:Int = 2
for (j in 1..4)
print(j) // prints "1234"
if (i in 1..10) { // equivalent of 1 < = i && i < = 10
println("we found your number --"+i)
}
}
This will return the following output:
1234Here is your number — 2
That’s all for now. Check back soon for the next article in the series where we’ll take a look at Control Flow in Kotlin. See you then.
Next Article: Control Flow in Kotlin |
Recent Stories
Top DiscoverSDK Experts
Compare Products
Select up to three two products to compare by clicking on the compare icon () of each product.
{{compareToolModel.Error}}
{{CommentsModel.TotalCount}} Comments
Your Comment