Kotlin Lang Quickstart

By pjain      Published Dec. 15, 2019, 7:21 a.m. in blog Programming   

Kotlin Lang QUIK

Lang like Java

//  and /* multi-line */
package com.gomobilefirst.example  // like java

concise syntax

; <- optional


Types - strong typing and inference is important

fun main(args: Array<String>) { println("Hello World") }

val x = 0; var mut = 1
x += 1   // <-- compiler complains
mut += 1  // no problem


+ concatenate
"created $datein" // string templates
val out = "$fooString has ${fooString.length} characters"
val s = """ Multiline Strings

var, val

     var x: String = "abc" // normal mutable var - :String imputed
     val y="xyz" //immutable

Int val x = 13 //32bit

Long x=324L //64bit

Float y=3.14f obj.toFloat()

Double d=3.14 obj.toDouble()

Boolean true false


  • Java - all variables can be null - can create exception or runtime crashes. By explicitly handling this, static checking can ensure this.

    • MUST declare as TYPE? if can be null - otherwise will give exception if declared or set to null
    • ?. operator can be chained - member1?.member2()?.member3()

      val nullable: String? = null val alternative = nullable ?: "¯_(ϑ)_/¯" // since nullable is null - assigns alternative to the string

  • Conditional nullable assignment val lengthOrNull = nullable?.length // infers as Int, assigns as null if (nullable != null) { println(nullable.length) }

  • Testing nullable variables

    • ?: Elvis operator - ternary operator to test null in else condition var currentTime: java.util.Date? = null println( currentTime?.getTime() ?: -1 ) // returns -1 as currentTIme is null ..

    • !! operator - null pointer exception - bypass the null check and throw null pointer exception The null check safety IS still done - only throws exception instead of compile time ...

null safety check reqd for objects or use primitives

var artist: Artist? = null  // var artist: Artist = null <--- won't compile
artist?.print()  // or just test if (artist!=null) {print() } - null safety check reqd!
artist!!.print() // only use if CERTAIN it is not null .. try never to use !! - ANE
val name = artist?.name ?: ""

Functional Support

fun Int.twice() = this * 2 
fun test() = 1.twice() !/2

Lambdas, let/it

fun f() : Int   // return  or empty or : Unit

view.setOnClickListener { toast("Hello world!") }


  • Optionals/default values for named arguments - reduces need to declare multiple methods/overloading

    fun Activity.toast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
 Toast.makeText(this, message, duration)
.show() } toast("in onCreate") // or toast("in onCreate", Toast.LENGTH_LONG) since 2nd arg is optional toast(duration = Toast.LENGTH_LONG, message="something") // named parms

    Note: you can use optional args in default constructor as well - to get MANY constructors in 1 declaration.

KT OOP, Class 101 : instead of extends, methods Need fun

k forces explicit use of ‘override’

POJO = data class

  • data Class achieves - constructor, getters,setters, equals, hshCode, toString all in 1 line
  • ?? Does it have a SQLite model interface?

    data class Artist(var id: Long, var name: String, var url: String, var mbid: String)

    data class Money(val amt:Int, val currency: String) //<-- this is the default constructor

    val tickets = Money(100, "$") val popcorn = tickets.copy(100,"$") // = single or .copy() no parms - means exact copy if (tickets != popcorn) println("Different") // Property one by one compare - - so will be SAME! if (tickets !==popcorn) println("Differnt") // !== triple exact object compare will always be different?

StdLib, IO

Common Functions, Std Lib

  • console, Logging print("Hello, World!") println("Hello, World!")

Files packages

Packages are optional 
no need to match folder

Files can have multiple classes 
top level functions

Packages, Lang Mastery, Playgrounds

Packages running at cmd line, REPL

package my.com  // optional wrapper - useful for android access from manifest.xml etc .. 
import java.util.* // all JVM functions callable

fun main(args: Array&lt;String&gt;) {println("Hello, World!") }
$ kotlinc hello.kt -include-runtime -d hello.jar
$ java -jar hello.jar  # &gt; "Hello, World!
// Note: k-class loader doesn't require matching package trees &amp; file directories ..


  • $ kotlinc-jvm # :help :quit :dump bytecode :load FILEPATH # on windows you need to save with Eunx EOL not CR/LF

r Sort

Official website goo.gl/xL99fk Kotlin and Android(blog) goo.gl/FQYAcW Introduction to Kotlin(video) goo.gl/3n6wic Life is Great and Everything Will Be Ok, Kotlin is Here(video) goo.gl/NTaYqi Using Project Kotlin for Android(doc) goo.gl/T0SDTJ

  • Roadmap The Future of Kotlin(video) goo.gl/INLPDl Kotlin 1.1(video) goo.gl/iKojmn

  • Android Watch more Android talks at I/O '17 here: https://goo.gl/c0LWYl


There are no comments yet

Add new comment

Similar posts

mr UXD and Prototyping Tools

SOA Api Metadata

Serverless Computing

Android Layouts Design 101