Category: Kotlin

Kotlin Use function

Kotlin Use function

Kotlin Use function is an inline function used to execute given block function on this resource. Use function closes the resource correctly once after the operation is completed. There is an added benefit that even if there is an exception while executing the given block function, it is expected that the resource is closed down correctly.

Use function could be thought of as try with resource in Java.

Syntax of Kotlin Use function

Following is the syntax of use function

inline fun <T : Closeable?, R> T.use(block: (T) -> R): R (source)

block is the function to process the Closeable resource.

fun returns the result of block function.

 

Example of Kotlin Use function

contents.txt is in input folder which is next to UseFunctionExample.kt

 

Conclusion :

In this Kotlin Tutorial, we have learnt to use Kotlin Function on a resource.

Kotlin Interview Questions

Frequently asked top Kotlin Interview Questions and Answers with detailed example programs and references. Links would be provided at appropriate junctures in the answers. You may refer those in case you need any clarification. Sequential reading of questions and answers is suggested, as it simulates a kind of interactive session.

 

Why did you switch to Kotlin from Java ?

Kotlin seems to be simpler and cleaner than Java. It removes a lot of redundancies in code from Java. Kotlin also adds some needed features that Java doesn’t yet support, and is making code more idiomatic. Also Kotlin has been added to Android Studio’s list of supported languages recently. So, there is much to expect from Kotlin in easing out the development efforts and good support in future.

 

What are the features you think are there in Kotlin but not in Java ?

Kotlin has quite a number of features that Java doesn’t. To name some of them, they are

  • Extension Functions
  • Null Safety
  • Smart casts
  • Range expressions
  • Operator Overloading
  • Data classes
  • Companion Objects
  • Coroutines
  • etc.

 

What kinds of programming does Kotlin support ?

Kotlin supports two types of programming. They are

  1. Procedural Programming
  2. Object Oriented Programming

 

What is the entry point to a Kotlin program ? Provide an example.

Like most of the other procedural languages, main() function is the entry point to a Kotlin program.

An Example for main() function is :

Reference – Kotlin main function

 

How do you think extension functions are useful ? – Kotlin Interview Question

Extension functions helps to extend a class with new functionality without having to inherit from the class. Also you may use them like an inbuilt function for the class throughout the application.

Reference – Kotlin Extension Functions

 

What are Data classes ? Aren’t they available in Java ? – Kotlin Interview Question

Sometimes we use a class just to hold the data and nothing else. These classes are called Data classes. Of course these kind of classes could be built using Java, but with explicit implementation of getter and setter for each of the properties of class. Also you may need to implement functions like equals, toString and copy separately. What Kotlin does is implementing all these automatically along with special functions called component functions. How cool is that, removing the redundant code bloat.

Reference – Kotlin Data Class

 

Does Kotlin provide any additional functionalities for standard Java packages or standard Java classes? – Kotlin Interview Question

Ofcourse, Yes. Kotlin uses the concept of extension functions, that we already talked about, to build some useful and more widely used functions among developers directly into the Kotlin library.

 

Hmm! Where does this Kotlin run ? Does it have some kind of different runtime environment ?

Once compiled, Kotlin programs can run on standard JVM like some other compiled Java code. This means that Kotlin Compiler compiles Kotlin programs to byte-code, which is understood by JVM. So, Kotlin is like a flavor of Java, that goes alongside Java. Interesting fact is that, Kotlin applications can be built with parts of Java code.

 

So, how do you migrate the code from Java to Kotlin ? – Kotlin Interview Question

JetBrains IDEA provides inbuilt tools to convert Java code to Kotlin code. Then you may do the magic offered by Kotlin at some of the parts in code, to make it clean.

Reference – Convert Java File to Kotlin File

 

OK. Is there something called init block in Kotlin ?

Yes.

 

What does init block do and Where does it appear in a class ? – Kotlin Interview Question

Instructions in the init block are executed right after Primary Constructor’s execution. init block goes in a class along with secondary constructors as a method.

Reference – Kotlin Init

 

What is the difference between val and var ? – Kotlin Interview Question

Val (Value) is like a constant. Once assigned a value, you cannot change it. On the other hand Var (Variable) is designed to be a storage location that can accept reassignment of values of same data type or what ever feasible by the data type casting.

Reference – val vs var in Kotlin

 

What is Kotlin’s Null Safety ? – Kotlin Interview Question

Null Safety in Kotlin is to eliminate the risk of occurrence of NullPointerException in real time. Kotlin can differentiate between nullable references and non-nullable references. If a variable has to be allowed to store a null value, that has to be declared with a null (?) operator.

Reference – Null Safety in Kotlin

 

If you have worked with files, name some of the extension methods Kotlin provides to java.io.File

Kotlin provides very useful extension functions to java.io.File. Some of them are :

  • File.bufferedReader() : to read contents of a file into BufferedReader
  • File.forEachLine() : to read a file line by line in Kotlin
  • File.inputStream() : to read contents of file to InputStream
  • File.readBytes() : to read contents of file to ByteArray
  • File.readLines() : to read lines in file to List
  • File.readText() : to read contents of file to a single String

For  examples to these methods refer – Kotlin Read File Content

 

Is there Ternary Conditional Operator in Kotlin like in Java ?

No.

 

How do you realize Ternary Conditional Operator in Kotlin ?

A simple if else should do the job.

 

How do you declare a variable as volatile in Kotlin ? – Kotlin Interview Question

By providing volatile annotation before the declaration of variable.

 

How do you check if two Strings are equal valued ? – Kotlin Interview Question

Using == (double equal to) operator.

Reference – Kotlin compare Strings

Val vs Var in Kotlin

Kotlin Tutorial – Val vs Var in Kotlin – We shall learn the difference between the usage of keywords val and var in Kotlin Programming Language with Example Kotlin programs.

 

Val vs Var in Kotlin

Let us first look into the actual names of these keywords and then we shall see how Kotlin Programming Language allows us to use these two keywords with examples.

Var – Variable – The object stored in the variable could change (vary) in time.

Val – Value – The object stored in val, could not vary in time. Once assigned the val becomes read only, like a constant in Java Programming language. The properties of the object (as Val) could be changed, but the object itself is read-only.\

 

Assign and change value of Var for a basic data type

We shall look into an example where we shall assign some data to val and var, and try to change the values they hold.

The value of a var could be changed.

 

Assign and change value of Val for a basic data type

We shall look into an example where we shall assign some data to val and var, and try to change the values they hold.

Kotlin compilation Error – Val cannot be reassigned occurs.

 

Assign and change properties of Val object

We shall look into an example where we shall declare an object to val and try changing the values of its properties.

We have used Data Class in Kotlin to realize properties of an object. The properties of a val object could be changed.

 

Conclusion :

In this Kotlin Tutorial, we have learnt about Val vs Var in Kotlin that var could be changed at any level. Whereas val once assigned, could not be changed, but its properties could be changed.

Kotlin Enum Classes

Kotlin Enum Classes

Kotlin Enum – Enum is a special data type that allows a variable to hold a value only from a set of predefined constants.

In this tutorial, we shall learn about Kotlin Enum Class : Syntax, Initialization, how enum classes are different from regular classes. An example program is provided to demonstrate the usage of Kotlin Enum.

Syntax :

Following is the syntax to define an Enum class in Kotlin

enum class <enum_class_name> {
    constant1, constant2, constant3
}

Any number of constants could be specified inside the class separated by comma. Each Enum constant is implicitly an Object of type <enum_class_name>.

Following is an example of defining a Kotlin Enum class “MobileColor” :

 

Kotlin Enum Initialization

As Kotlin Enum is an object of an Enum class, these could be initialized. We shall use the same example of MobileColor enum class to demonstrate the initialization of enums.

Kotlin Enum

 

Kotlin Enum Example – To demonstrate the usage of Enum Classes

Following example demonstrates the usage of enum class MobileColor. Data Class, Mobile, has a variable as Enum class, MobileColor Object.

 

How enum class is different from a regular class

You cannot create new instances of an Enum class outside of its definition. In other words outside enum definition, you cannot create an object of type Enum Class by passing values to its primary constructor. You may do so for regular classes.

Conclusion :

In this Kotlin Tutorial, we have learnt about Enum Classes in Kotlin with a Kotlin Example to understand the usage.

How to read file content as a list of lines in Kotlin – Kotlin Example

Kotlin Tutorial – Learn how to read file content as a list of lines in Kotlin. Kotlin Example is provided with File.readLines() to read content line by line from file.

Function to be used to read the lines from file :

File.readLines()Reads file content as a list of lines

Read file content as a list of lines in Kotlin – Kotlin Example

Read lines in Text file

Contents of file is shown below :

Hello World.
Welcome to Kotlin Tutorial by www.tutorialkart.com.
Learning Kotlin is easy.

Conclusion :

In this Kotlin Tutorial, we have learnt to read content of file line by line.

How to iterate through all files in a directory using Kotlin – Kotlin Example

Kotlin Tutorial – Learn to traverse or iterate through all files in a directory using Kotlin. We shall present you a Kotlin Example program to demonstrate on the same.

We shall use the extension functions  of java.io.File : walk(), walkBottomUp, walkTopDown()  to generate kotlin.io.FileTreeWalk on which we use iterator to traverse the directory and its contents. The functionality of the three functions is almost same except the order in which they iterate through contents.

Kotlin Examples – Traverse or iterate through all files in a directory using Kotlin

Traverse or iterate through all files in a directory using Kotlin - Kotlin Example - Kotlin Tutorial - www.tutorialkart.com

walk() – using java.io.File.walk()

walkBottomUp() – using java.io.File.walkBottomUp()

walkTopDown() – using java.io.File.walkTopDown()

Conclusion :

In this Kotlin Tutorial, We have successfully learnt to traverse or iterate through all files in a directory using Kotlin Examples.

 

How to Compare Strings in Kotlin – Kotlin Example

Compare Strings in Kotlin

To Compare Strings in Kotlin, following are some of the possible ways :

Using “==” Operator

We shall use ==  operator for comparing two Strings in Kotlin. According to the documentation of Equality in Kotlin,  ==  operator is used for Structural Equality.

a==b  is implicitly translated to  a?.equals(b) ?: (b === null)  by Kotlin language.

Make sure that the two values a  and b  are of type Strings. Else convert them to Strings before comparison.

Example

 

Using compareTo() extension function

Kotlin provides compareTo() extension function to String.

Syntax of compareTo() function is given below :

other: String is mandatory argument.
ignoreCase is optional.

The function returns integer value.

Return ValueDescription
0The two strings are equal.
negative integerIf the string is less than the other string
positive integerIf the string is greater than the other string

Example

 

Conclusion :

In this Kotlin Tutorial – Compare Strings in Kotlin, we have learnt to compare two strings using == Operator and CompareTo String function, with the help of example programs.

How to connect to MySQL Database from Kotlin using JDBC

Kotlin Tutorial – We shall learn to connect to MySQL Database from Kotlin using JDBC with the help a Kotlin Example Program.

Following is a step by step process explained to connect to MySQL Database from Kotlin using JDBC :

  • Step 1 : Add MySQL connector for java

    MySQL connector for java works for Kotlin as well. Download MySQL connector for java, mysql-connector-java-5.1.42-bin.jar , from https://dev.mysql.com/downloads/connector/j/5.1.html. Open IntelliJ IDEA, Click on File in Menu, Click on Project Structure, Click on Libraries on the left panel, and add the jar to Libraries.

    Add MySQL jar to Kotlin Java Runtime Library - Connect to MySQL Database from Kotlin using JDBC - Kotlin Tutorial

    Add MySQL jar to Kotlin Java Runtime Library

  • Step 2 : Establish a connection to MySQL Server

  • Step 3 : Execute MySQL Query to show DATABASES available

Kotlin Example Program to connect to MySQL Database from Kotlin using JDBC

 

Conclusion :

In this Kotlin Tutorial, we have learnt to connect to MySQL Database from Kotlin using JDBC with the help of Kotlin Example Program.