Android-Kotlin Digest #5 – Null Safety

One of the most irritating things in programming is apps crashing due to null / nil objects.

In Objective-C, you can call a method on nil objects it wont crash but it will never ever give expected result and we developers end up debugging a whole lot of our time searching out for the culprit.

In Java it used to be NullPointerException (NPE). And reason for app crashes.

Modern languages solves this problem by having the null safety mechanisms.

Swift uses Optionals ? and Unwrapping ! the optionals. Swift also has if let and guard let statements for safely unwrapping the optionals and handle in case of nil values.

Here on the same lines we will discuss about how Kotlin ensures Null safety

var str: String = "abcd"
str = null // This line gives a compilation error

var str: String? = "abcd"
str = null // This pass thru since str is declared String?

Now suppose you want to check the length of str in case of optional, to do it safely you need to typically:

val len = if (str != null) str.length else -1

Or else use safe call operator ( ?. ) like : str?.length

(In swift we call it Optional chaining)

In Kotlin, the former if else statement can also written using what is called elvis operator ( ?: )

val len = str?.length ?: -1

And if developers are sure of an reference having a value then use not-null assertion operator ( !! )

val len = str!!.length

(Problem with this is if the reference is null the NullPointerException is thrown)



Android-Kotlin Digest #4 : A simple way to Read and Write

Here I will give you an overview of :

– how to read user input from command line?

– how to read data from a file?

– how to write to a file?

How to read user input from command line?

println(" ->Welcome to our Bakery<-")


println("Hello! How can I help you?")

var userResponse = readLine()

println("Sure!!" + "It's fresh prepared just now!")

var userNextResponse = readLine()

println("You are very welcome! Have a nice day!")

println("================== ====================")

println(" :: Your Conversation with the Clerk :: ")

println("Clerk: Hello! How can I help you?")

println("Customer: $userResponse")

println("Clerk: Sure!! It's fresh prepared just now!")

println("Customer: $userNextResponse")

println("Clerk: You are very welcome! Have a nice day!")

How to read data from a file?

val reader = FileReader("itsdamslife.txt")
var char: Int?
try {
do {
char =
} while (char != -1)
} catch (exception: Exception) {
print("There was an exception : $exception.message")


How to write to a file?

try {

    var writer = FileWriter("itsdamslife.txt", true)
writer.write(message + "\n")
} catch (exception: Exception) {
println("There was an exception :  $exception")

Android-Kotlin Digest #3 – A gist of Collection types

Today in Kotlin, learnt about Arrays, Hashmaps, ArrayList, MutableList, MapOf, ArrayOf. Here is gist of things.

In Swift we have all the functionalities of Array in one place.

In here Kotlin we may need to use combination of Array and ArrayList.

Here are few Kotlin examples:


var myArray = Array<Int>(6){2}
for (element in myArray) {
println("Item - " + element)

for (index in 0..myArray.size - 1) {


var myArrayList = ArrayList<String>()

if (myArrayList.contains("Coders"))
println("He's a rockstar!")


//iterating through objects
for (names in myArrayList) {
println("Names:" + names)

HashMap: (Dictionary in Swift)

var hashmap = HashMap<String, String>()
hashmap.put("Mary", "Married")
hashmap.put("Paulo", "Married")
hashmap.put("John", "Single")

for (k in hashmap.keys)

Other Collection Utilities:

var myArrayList = listOf<String>("Me", "James", "Bonni", "Life")
var mutableList = mutableListOf<String>("Me", "They", "James")
var myHashmap = hashMapOf(1 to "Paulo", 2 to "James")

Android-Kotlin Digest #2 – Basic Types

Back again with Kotlin I learnt.

Kotlin runs on Java Virtual Machine (JVM).

Syntax for declaring variables:

Mutable:     var name: Type = value

Immutable: val name: Type = value

Type Bit width
Double 64
Float 32
Long 64
Int 32
Short 16
Byte 8

Kotlin 1.1 supports underscores ( _ ) in numeric values for readability:

val mySalary = 1_000_000

val myCreditCardBill = 20_000

Difference between == and === :

val a : Int = 10

val b : Int = 10

(a == b) // gives true 

(a === b) // gives true 

Note: Here primitive types are compared.

When the primitive types are nullable it is turned into references and following is the result:

val a : Int? = 10

val b : Int? = 10

(a == b) // gives true 

(a === b) // gives false 

Note: Here a and b becomes references and hence comparision with === results false.

Type converters:



A raw string is delimited by a triple quote (“””), contains no escaping and can contain newlines and any other characters:

val text = “””

    for (c in “foo”)



You can remove leading whitespace with trimMargin() function:

val text = “””

    |Tell me and I forget.

    |Teach me and I remember.

    |Involve me and I learn.

    |(Benjamin Franklin)


— Happy Coding —

Start with this to have a work-life balance

A slightly off topic from technology this time, but somewhat related to. I wanted to share this as most of us face this question or being asked, hence writing this post.

In today’s world of extreme competition and

I went through these questions myself

  • Do you have a perfect Work-Life balance?
  • What is a work-life balance?
  • How do you measure the balancing part?

Finally ended up at – Whatever makes me and my family happy proportionately. Since we all have only 24 hours a day we need to divide according to the needs.

Work definitely takes up major part of our day followed by a good sleep. How to stay healthy and fit along with being competitive at work updating with latest technology and keep family happy. Spending time with family is also like a break which is more needed everyday.

So I divided my awake time into these basic things

  • Work
  • Family
  • Studies
    • Improving in areas related to Work
    • Learning new things which helps your career – unrelated to work
  • Personal interests

Dividing your time among these.

Work – Typically 8-9 hours per day + commute time 1 hour to&fro (I will tell you how to utilise if this is more)

Family – You need to spend a minimum of 1.5 – 2 hours per day on week days. And 1 out of 2 days on weekend, either divide it half day each per day or 1 full day at stretch.

Studies – With today’s rapid change in technologies and young fresh workforce available to work harder grabbing every opportunity, we need to strive harder not just keeping up the pace but to be better at the competition. So we need to be updating and upgrading ourselves every single day. This becomes more critical:

  • Improving in areas related to Work – if done consistently an hour every day suffices. Also learning on the go at work, discussing with colleagues is best possible way to improve yourself –  1 hour/day
  • Learning new things which helps your career, unrelated to work, is basically for expanding your horizon as you grow. One hour a day or at-least 5 hours a week consistently must get you going.

Personal interests – This here is anything you want to pursue in your life or life the way you want. (For example I want to: go on bike rides, see different places, try different  cuisines, understand different cultures, learn more about life.) Allocate some time for this cause this is what makes you happy, brings you to life, brings on a change to your routine and fills energy to your life – 30-60 minutes per day.

there should be something which is why you are living for yourself and you must do that or work towards that

This can be daily short routine or weekly routine or twice a year routine. But finally there should be something which is why you are living for yourself and you must do that or work towards that.

Sleep & workout: To stay healthy and fit a human must have at least 6-8 hours of good sleep and a minimum of 30 mins of workout in the form of Yoga or hitting the gym.

Commute Time: As said above if its more than an hour per day use your commute time to accommodate your reading or listening to podcasts. Avoid driving yourself use office transport or any others in which you can focus on progressing on your personal interests or any trivial tasks. In the evenings way back home habituate taking a nap, this refreshes you when you reach home and be energetic when you spend time with family.

Hope this post has helped you in one or other form at least get you started on thinking how you can divide time and accordingly plan your daily life.

Have a great life!

Android-Kotlin Digest #1

Planning to journal updates on my learning in Android and Kotlin development. This would be mostly from an ​iOS developer’s perspective. I will be writing gist of what I learnt today and anything specific interesting.

To start off below are some things I learnt in Kotlin and differences with Swift.

Some basics of Kotlin:

var of mutable variables

val of immutable variables / constants

Adding variable value in a string "The value of variable is $variable_name"

Suffix ? for variables holding null values

Also has a javascript big arrow => function like syntax:
fun sum(a: Int, b: Int) : Int = a + b

Conditionals: `if (obj is String) { … }` and not checks `if (obj !is String) { … }`

I found switch statements most unique till now:

when (obj) {
1          -> "One" // (case)
"Hello"    -> "Greeting" // (case)
is Long    -> "Long" // (case)
!is String -> "Not a string" // (case)
else       -> "Unknown" // (default case)

Ranges are specified as 0..end or 0..end+1 or 0..list.lastIndex

Then we have progressions:

for (x in 1..10 step 2) {
Jumps alternate steps with keyword `step` and value 2. Here result would be: `13579`

for (x in 9 downTo 0 step 3) {

Jumps three steps but in reverse order with keyword `downTo`. Here result would be: `9630`


Hey there!!

This is a post since long time. Today I am trying out _Micro.blog_ a micro blogging website. Looks fine confusing at beginning.

This is like a test post from cross posting into WordPress. I have connected WP in my account.