Android — Kotlin Basics to Advance Interview preparations coding practice

iamVariable
8 min readOct 7, 2023

Hi Guys, we gonna see some of the basic to advance interview preparation article. Dont stop reading this, just give a try so that you will understand easily.

Lets start with Variable declaration,

Variable declaration:

//one way of declaration (Float)
val myFloatValue :Float = 0.00456f
//another way of declaration (FLoat
val myFloatValue2 = 0.00456f
//or if you want to declare a nullable float value then just add (?) over there
var myFloatValue :Float? = 0.00456f

//similarly string
val myStringValue :String = "Hi Developers"
//or
val myStringValue1 = "Hi Developers"

Here if you’re not mention (f) then Kotlin complier will consider as double. Some other ways also there. But these are the common way of declaration.

Array Declaration:

//Declare an array of type non-nullable Int
val myIntArray : Array<Int> = arrayOf(10,15,20)
//or
val myIntArray1 = arrayOf(10,15,20)

Same way Initialize with some sequence values in simple format

//here we declare with nullable Int 
//this code will execute the sequence of 5,10,15...100 as we mentioned 40 array size
val intArray = Array<Int?>(20) { i ->
(i + 1) * 5
}

Calling a java method from kotlin:

java method as follows

public void myMethod(char[] myCharArr) {
//do some stuff
}

Now we gonna see pass some char from kotlin to this above java method

val myCharArray = charArrayOf('a','b','c')
myMethod(myCharArray)

Using Elvis (?:) operator:

//given string 
var myString: String? = "I AM A KOTLIN DEVELOPER"
// now check if the myString is null, assign "OOPS, NOTHING TO SHOW"
//for that declare another variable to assign
val myString1 = myString ?: "OOPS, NOTHING TO SHOW"

Using Let function:

User the same example string here

//given string 
var myString: String?= null
myString = "I AM A KOTLIN DEVELOPER"
// now check if the myString is null, assign "OOPS, NOTHING TO SHOW"
//for that declare another variable to assign
myString?.let {
println(it.lowercase().replace("kotlin", "Android")
}

Modifiers:

We have major 4 modifiers in Kotlin as other programming languages. Those are listed,

  • private (only visible inside the class only)
  • protected (visible inside the class and its children class)
  • internal (only visible the same package)
  • public (anyone can see, and by default its public)

Example we see here

where as if I add private to the Airplane variables / functions

Incase, if I change the same parent variable/function to protected,

The next example with internal

Hope now it clarifies clearly. Lets jump into the OOPS next.

OOP Concepts:

There are 4 main priciples of Object Oriented Programming in Kotlin. A set of guidelines that make a language object-oriented.

As a developer, if we follow these OOP cpmcept then you help other developers to understand your code quite easily.

  • Inheritance (classes can inherit methods and variables from other/super classes)
  • Encapsulation (As we knew, its just Hiding data and inner working of a class from other classes that dont need to know how it works)
  • Abstraction (A common feature of 2 classes should be abstracted in third class)
  • Polymorphism (Same name with namy forms)

* Inheritance:

open class Dad {
//variable declaration
val hairColor = "Brown"
val eyeColor ="Blue"
// fun declaration
fun sayHey(name: String) {
println("Hey $name")
}
}
class Son : Dad() {
}
fun main(args:Array<String>) {
val mySon = Son()
mySon.sayHey("Martin") // Hey Martin
//print the variable
println(mySon.eyeColor) // Blue
}

In the same example, if the parent class (Dad) has motherTongue param in it’s constructor then let’s see how it will get change,

open class Dad(private val motherTongue:String) {
//variable declaration
val hairColor = "Brown"
val eyeColor ="Blue"
// fun declaration
fun sayHey(name: String) {
println("Hey $name, I speak $motherTongue")
}
}

class Son(motherTongue:String) : Dad(motherTongue) {
}

fun main(args:Array<String>) {
val mySon = Son("Tamil")
mySon.sayHey("Martin") // Hey Martin, I speak Tamil
//print the variable
println(mySon.eyeColor) // Blue
}

If you want to change the some details according to your need in your children class, you must change the variable or function to open.

open class Dad(val motherTongue: String) {
//variable declaration
val hairColor = "Brown"
open val eyeColor = "Blue"
// fun declaration
open fun sayHey(name: String) {
println("Hey $name, I speak $motherTongue")
}
}

class Son(motherTongue: String) : Dad(motherTongue) {
override fun sayHey(name: String) {
println("Hey, I am your son, and I Speak $motherTongue")
}
override val eyeColor: String = "brown"
}

fun main(args: Array<String>) {
val mySon = Son("Tamil")
mySon.sayHey("Martin") // Hey, I am your son, and I Speak Tamil
//print the variable
println(mySon.eyeColor) // brown
}

Hope you get some clear idea about Inheritance. Next we gonna see Encapsulation

* Encapsulation

Here we see some encryption concept, you can see the formula to unlock the key is private. Other classes cannot access the “ formulaToUnlock” function outside. So the main functionality has been hidden.

class Encryption(private val privateKey: Int) {
fun unlockMyKey(publicKey: Int) = formulaToUnlock(publicKey) == privateKey
private fun formulaToUnlock(publicKey: Int) = publicKey * 2 + 5
}
fun main(args: Array<String>) {
val encryption =Encryption(37)
println("PrivateKey is 16 and unlock result is ${encryption.unlockMyKey(16)}") //PrivateKey is 16 and unlock result is true
println("PrivateKey is 36 and unlock result is ${encryption.unlockMyKey(36)}") //PrivateKey is 36 and unlock result is false
println("PrivateKey is 46 and unlock result is ${encryption.unlockMyKey(46)}") //PrivateKey is 46 and unlock result is false
}

* Abstraction

A functionality that is not associated with an instance (object) and should be away. In clear, if two different classes shares a common feature, tehn create a super class that contains the common feature and inherit from it.

By this, we can avoid the code duplication. The Keyword abstract to be used. Let’s jump into the example.

Another important thing, YOU CANNOT CREATE OBJECT FOR THE ABSTRACT CLASS.

if you, haven’t mention the abstract keyword to the particular funtion, you cannot use the same function name in your children class.

If you mention abstract you cannot use the implementation there over.

Here is the correct way of implementation.

* Polymorphism

As we know, poly means many. A mothod / function that can do different things in different situations. There are 2 types of polymorphism.

  1. Dynamic (Method overriding)
  2. Static (Method overloading)

Let’s jump to lean Method Overriding

open class Mom {
open fun sayHello(message:String){
println("Mom Says Hello $message")
}
}
class Daughter : Mom() {
override fun sayHello(message: String) {
println("Daughter Says Hello $message")
}
}
fun main(args: Array<String>) {
val mom = Mom()
val daughter = Daughter()

mom.sayHello("Welcome")
daughter.sayHello("Welcome")
}

Method Overloading

This will have same function/method name but with different parameters

open class Mom {
open fun sayHello(message: String) {
println("Mom Says Hello $message")
}
fun sayHello() {
println("Mom Says Hello")
}
fun sayHello(age: Int) {
println("Mom Says Hello,I am $age")
}
fun sayHello(name:String,age: Int){
println("Mom Says Hello,I am $name and I am $age years old")
}
}

fun main(args: Array<String>) {
val mom = Mom()
mom.sayHello("Welcome") //Mom Says Hello Welcome
mom.sayHello(55) //Mom Says Hello,I am 55
mom.sayHello("Rani",55) //Mom Says Hello,I am Rani and I am 55 years old
}

* Interfaces

Simple example for interface is here, If you see this example in the Interface we declared one String and one Int data type as well. We all know the fun always override when you implement this interface. But how the variable will react when it implement? So simple see the example.

interface Cat {
val breed: String
val weight: Int
fun printMe();
}

fun main(args: Array<String>) {
val myCat: Cat = Tiger("BreedA", 3)
println("My cat is a ${myCat.breed} that is ${myCat.weight}KG")
}

class Tiger(override val breed: String, override val appearance: Appearance) : Cat {
override fun printMe() {
println("Printing function");
}
}

Data Class:

If you already aware of java, its similar to POJO class. Commpnly create data classes to store the data.

  • Primary construction must have at least one parameter
  • all primary constructor parameter need to be val or var
  • may have also body, but generally not needed

Examples, compare normatl class with data class.

class User (
val name:String,
val age:Int
)
fun main(args: Array<String>) {
val user1 = User( "A",10)
val user2 = User("A",10)
println(user1 == user2) //false bcz, it compares the references and its totally diff objects
println(user1) //User@266474c2
}

But, just add ‘data’ infornt of the class and see the result

data class User (
val name:String,
val age:Int
)
fun main(args: Array<String>) {
val user1 = User( "A",10)
val user2 = User("A",10)
println(user1 == user2) //true bcz, it compares the value
println(user1) //User(name=A, age=10)
//copy
val user3 = user1.copy(name = "B")
println(user3) //User(name=B, age=10)
}

Enum classes:

It helps to judge or compare constant values. Its Defined as collection of constants.

enum class Colors {
RED,
BLUE,
GREEN
}

fun main(array: Array<String>){
val color = Colors.GREEN
when(color){
Colors.RED -> println("RED")
Colors.BLUE -> println("BLUE")
Colors.GREEN -> println("GREEN")
}
}

Enum constants can be initilized, also we can get the position (ordinal) lets see example for this,

enum class Colors(val times:Int) {
RED(100),
BLUE(29),
GREEN(56)
}

fun main(array: Array<String>){
val color = Colors.GREEN
when(color){
Colors.RED -> println("RED")
Colors.BLUE -> println("BLUE")
Colors.GREEN -> println("GREEN") //GREEN
}
println(Colors.RED.times) //100
println(Colors.BLUE.ordinal) //1
println(Colors.GREEN.name) //GREEN
}

Sealed classes:

Sealed class are abstract by default so, as said we cannot create object for these classes.

Mainly useful in when expression, let’s see the example

abstract class Plant

sealed class Fruit : Plant()
sealed class Vegetable : Plant()

class Apple : Fruit()
class Potato : Fruit()

fun main(array: Array<String>) {
val obj = Apple()
when (obj) {
is Fruit -> println("Sweet fruit") // sweet fruit
is Vegetable -> println("Tasty Vegetable")
}

val obj = Potato()
when (obj) {
is Fruit -> println("Sweet fruit")
is Vegetable -> println("Tasty Vegetable") //Tasty Vegetable
}
}

Testing:

  • Unit Test (using junit and Mockito for mocking)
  • UI Test (Espresso)

Happie coding :)

--

--

iamVariable

Experienced Mobile Application developer and in full software development lifecycle, including analysis, design, development, deployment.