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)

happyCoding!

Advertisements

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("============================")


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 = reader.read()
print(char.toChar())
} 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")
writer.close()
} 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:

Array:

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

for (index in 0..myArray.size - 1) {
println(myArray[index])
}


ArrayList:

var myArrayList = ArrayList<String>()
myArrayList.add("It's")
myArrayList.add("Coders")
myArrayList.add("Life")

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

myArrayList.remove("Coders")
myArrayList.add("Dams")

//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)
println(hashmap.get(k))


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:

‘c’.toInt()

80.toString()

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”)

        print(c)

“””

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)

“””.trimMargin()

— Happy Coding —