Skip to content

Instantly share code, notes, and snippets.

@Bhavdip
Last active October 9, 2017 13:55
Show Gist options
  • Save Bhavdip/259088e0f5745e1a3bb9a4db85357acc to your computer and use it in GitHub Desktop.
Save Bhavdip/259088e0f5745e1a3bb9a4db85357acc to your computer and use it in GitHub Desktop.
kotlin_tips_part2

Configuring Android Studio with Kotlin

@Bhavdip
Copy link
Author

Bhavdip commented Oct 9, 2017

Variables

In kotlin, we have two types of variables: var or val.
The first one, var is a mutable reference (read-write) that can be update after initialization.
The var keyword is used to define variable in kotlin. It is equivalent to a normal (non-final) java variable.
If our variable needs to change at some point, we should declare it using var keyword.

fun main(args: Array<String>){
  var fruitName = "orange"
   fruitName = "bannan"
}

val keyword is equivalent of a java variable with the final modifier. Using immutable variables is useful. it make sure that variable will never be updated by mistake. The concept is very helpful for working with multiple threads without worrying about proper synchronization.

fun main(args: Array<String>){
  val fruitName : String = "orange"
   fruitName = "bannan" //error
}

Strict Null safety

Strict Null safety is part of kotlin type system. By default regular type cannot be null.(can't store null references) unless they explicitly allowed. To store null references, we must variable as nullable( allow it to store null references) by adding question mark suffix to variable type declaration.

val age : Int = 1 // Compiler will thrown error because this type does not allow null. 
val age : string? = null // Compiler will allow assigned null because type is marked as nullable using question mark suffix.

We are not allow to call method on a potentially nullable object, unless nullity check is performed before a call:

val name : String? = null
..
..
name.upperCase() // error, these reference may be null 

@Bhavdip
Copy link
Author

Bhavdip commented Oct 9, 2017

Elivs operator

The Elivs operator is represented by a question mark followed by colon (?:) and has such syntax:

first operand ?: second operand

The elvis operator works follows: if first operand is not null, then this operand will be returned, otherwise second operand will be returned.
Note that the right hand side expression is evaluated only if left-hand side is null.

val correct  = quiz.currentQuestion?.answer?.correct ?: false 

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment