SlideShare a Scribd company logo
GETTING STARTED
Gradle
Android
In your build.gradle, use gradle setup and the android-kotlin plugins:

Gradle Options
Compilation tuning in your gradle.properties file:
Maven
Refer to the documentation online : http://kotlinlang.org/docs/reference/using-maven.html

BASICS
buildscript {
ext.kotlin_version = '<version to use>'
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
apply plugin: "kotlin"
dependencies {
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
android {
sourceSets {
main.java.srcDirs += 'src/main/kotlin'
}
}
apply plugin: 'com.android.application'
apply plugin:‘kotlin-android’
apply plugin:‘kotlin-android-extensions’ // if use extensions
Kotlin
Cheat Sheet
Kotlin is an open source statically typed language for the JVM. It can run on Java 6+ and bring smart
features to make your code concise and safe. Its high interoperability helps to adopt it very quickly.
Official documentation can be found at http://kotlinlang.org/
# Kotlin

kotlin.incremental=true

# Android Studio 2.2+

android.enableBuildCache=true
package mypackage


import com.package


/** A block comment

*/

// line comment
by
agiuliani@ekito.fr
@arnogiu
Values & Variables Definition
Val represents a constant value & var a mutable value

NULL SAFETY & OPTIONAL TYPING
Optional typing with <TYPE>?

Safe call (?.) or explicit call (!!.)

Defining default value with elvis operator (?:)

Late variable initialization with lateinit. You can also look at lazy initialized values

CLASSES
A simple Java POJO (Getter, Setter, Constructor) in one line

Public Visibility by default
All is public by default. Available visibility modifiers are: private, protected, internal, public
Data Class
By adding data keyword to your class, add toString(), equals(), copy() and exploded data (see
destructuring data below) capabilities

val a: Int = 1

val b = 1 // `Int` type is inferred

val c: Int //Type required when no initializer is provided

c = 1 // definite assignment
var x = 5 // `Int` type is inferred

x += 1
var stringA: String = "foo"

stringA = null //Compilation error - stringA is a String (non optional) and can’t have null value

var stringB: String? = "bar" // stringB is an Optional String

stringB = null //ok
val length = stringB.length // Compilation error - stringB can be null !

val length = stringB?.length //Value or null - length is type Int?
val length = stringB!!.length //Value or explicit throw NullPointerException - length is type Int
// set length default value manually

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

//or with the Elvis operator

val length = stringB?.length ?: -1
lateinit var myString : String // lets you define a value later, but is considered as null if not set
val myValue : String by lazy { "your value ..." }
class User (

var firstName: String,

var lastName: String,

var address: String? = null

)
by
agiuliani@ekito.fr
@arnogiu
Properties
Properties can be declared in constructor or class body. You can also limit access to read (get)
or write (set) to any property.

No Static, use Object !
You can write singleton class, or write companion class methods:

Closed Inheritance
The : operator, makes inheritance between classes and is allowed by opening it with open modi-
fier

FUNCTIONS
Function can be defined in a class (aka method) or directly in a package. Functions are declared
using the fun keyword

Default Values
Each parameter can have a default value

Named Arguments
When calling a function, you can freely set the given parameters by its order or by its name:

Function Extension
Kotlin allows you to define a function to add to an existing Class 

class User() {//primary empty constructor

constructor(fn: String) : this() { //secondary constructor must call first one

firstName = fn

}

var firstName: String = ""

val isFilled: Boolean // read only access property

get() = !firstName.isEmpty()
}
// my resource singleton

object Resource {

// properties, functions …

}
open class A()

class B() :A()
fun read(b:Array<Byte>, off: Int = 0, len: Int = b.size()) {

//...

}
fun String.hello(): String = "Hello " + this

// use the new hello() method

val hi = "Kotlin !".hello()
Kotlin
Cheat Sheet
read(myBytes, 0, myBytes.length) // old way to call

reformat(myBytes, len = 128) // using default values & named params
by
agiuliani@ekito.fr
@arnogiu
Lambda
A lambda expression or an anonymous function is a “function literal”, i.e. a function that is not
declared, but passed immediately as an expression 

- A lambda expression is always surrounded by curly braces,

- Its parameters (if any) are declared before -> (parameter types may be omitted), 

- The body goes after -> (when present). 

Destructuring Data
Sometimes it is convenient to destructure an object into a number of variables. Here is the easy
way to return two values from a function:

Data classes can be accessed with destructured declaration.

WHEN - A better flow control
when replaces the old C-like switch operator:

It can also be used for pattern matching, with expressions, ranges and operators (is, as …)

COLLECTIONS
Collections are the same as the ones that come with Java. Be aware that Kotlin makes differ-
ence between immutable collections and mutables ones. Collection interfaces are immutable.

Maps and Arrays can be accessed directly with [] syntax or with range expressions. Various of
methods on list/map can be used with lambdas expression :

val sum: (Int, Int) -> Int = { x, y -> x + y }
fun extractDelimiter(input: String): Pair<String, String> = …
val (separator, numberString) = extractDelimiter(input)
when (s) {

1 -> print("x == 1")

2 -> print("x == 2")

else -> { // Note the block

print("x is neither 1 nor 2")

}

}
// immutable list

val list = listOf("a", "b", "c","aa")

list.filter { it.startsWith("a") }
// map loop with direct access to key and value

val map = mapOf("a" to 1, "b" to 2, "c" to 3)

for ((k, v) in map) {

println("$k -> $v")

}
// write with mutable map

map["a"] = "my value"
// filter collection
items.filter { it % 2 == 0 }

by
agiuliani@ekito.fr
@arnogiu

More Related Content

What's hot (19)

PDF
Introduction to kotlin
NAVER Engineering
 
PDF
Taking Kotlin to production, Seriously
Haim Yadid
 
PPTX
Kotlin
YeldosTanikin
 
PDF
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Hardik Trivedi
 
PDF
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Tudor Dragan
 
PDF
The Kotlin Programming Language, Svetlana Isakova
Vasil Remeniuk
 
PDF
Swift and Kotlin Presentation
Andrzej Sitek
 
PPTX
Introduction to kotlin + spring boot demo
Muhammad Abdullah
 
PDF
Kotlin boost yourproductivity
nklmish
 
PDF
Little Helpers for Android Development with Kotlin
Kai Koenig
 
PDF
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan s.r.o.
 
PDF
Android antipatterns
Bartosz Kosarzycki
 
PDF
Kotlin - Better Java
Dariusz Lorenc
 
PDF
Coding for Android on steroids with Kotlin
Kai Koenig
 
PDF
Kotlin for Android devs
Adit Lal
 
PDF
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
PPT
The Kotlin Programming Language
intelliyole
 
PDF
Intro to Kotlin
Magda Miu
 
PDF
What’s new in Kotlin?
Squareboat
 
Introduction to kotlin
NAVER Engineering
 
Taking Kotlin to production, Seriously
Haim Yadid
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Hardik Trivedi
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Tudor Dragan
 
The Kotlin Programming Language, Svetlana Isakova
Vasil Remeniuk
 
Swift and Kotlin Presentation
Andrzej Sitek
 
Introduction to kotlin + spring boot demo
Muhammad Abdullah
 
Kotlin boost yourproductivity
nklmish
 
Little Helpers for Android Development with Kotlin
Kai Koenig
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan s.r.o.
 
Android antipatterns
Bartosz Kosarzycki
 
Kotlin - Better Java
Dariusz Lorenc
 
Coding for Android on steroids with Kotlin
Kai Koenig
 
Kotlin for Android devs
Adit Lal
 
(How) can we benefit from adopting scala?
Tomasz Wrobel
 
The Kotlin Programming Language
intelliyole
 
Intro to Kotlin
Magda Miu
 
What’s new in Kotlin?
Squareboat
 

Similar to Kotlin cheat sheet by ekito (20)

PDF
2 kotlin vs. java: what java has that kotlin does not
Sergey Bandysik
 
PDF
Exploring Kotlin
Johan Haleby
 
PDF
Privet Kotlin (Windy City DevFest)
Cody Engel
 
PDF
Kotlin: A pragmatic language by JetBrains
Jigar Gosar
 
PPTX
kotlin-nutshell.pptx
AbdulRazaqAnjum
 
PPTX
Hello kotlin | An Event by DSC Unideb
Muhammad Raza
 
PPTX
Introduction to Koltin for Android Part I
Atif AbbAsi
 
PDF
Kotlin intro
Elifarley Cruz
 
PDF
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
STX Next
 
PPTX
Introduction to Kotlin for Android developers
Mohamed Wael
 
PPTX
Kotlin presentation
MobileAcademy
 
PPTX
KotlinForJavaDevelopers-UJUG.pptx
Ian Robertson
 
PPTX
Introduction to kotlin and OOP in Kotlin
vriddhigupta
 
PDF
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Codemotion
 
PDF
Kotlin for Android Developers - 3
Mohamed Nabil, MSc.
 
PDF
Kotlin what_you_need_to_know-converted event 4 with nigerians
junaidhasan17
 
PPTX
Exploring Kotlin language basics for Android App development
Jayaprakash R
 
PDF
Bologna Developer Zone - About Kotlin
Marco Vasapollo
 
PDF
9054799 dzone-refcard267-kotlin
Zoran Stanimirovic
 
PDF
A quick and fast intro to Kotlin
XPeppers
 
2 kotlin vs. java: what java has that kotlin does not
Sergey Bandysik
 
Exploring Kotlin
Johan Haleby
 
Privet Kotlin (Windy City DevFest)
Cody Engel
 
Kotlin: A pragmatic language by JetBrains
Jigar Gosar
 
kotlin-nutshell.pptx
AbdulRazaqAnjum
 
Hello kotlin | An Event by DSC Unideb
Muhammad Raza
 
Introduction to Koltin for Android Part I
Atif AbbAsi
 
Kotlin intro
Elifarley Cruz
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
STX Next
 
Introduction to Kotlin for Android developers
Mohamed Wael
 
Kotlin presentation
MobileAcademy
 
KotlinForJavaDevelopers-UJUG.pptx
Ian Robertson
 
Introduction to kotlin and OOP in Kotlin
vriddhigupta
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Codemotion
 
Kotlin for Android Developers - 3
Mohamed Nabil, MSc.
 
Kotlin what_you_need_to_know-converted event 4 with nigerians
junaidhasan17
 
Exploring Kotlin language basics for Android App development
Jayaprakash R
 
Bologna Developer Zone - About Kotlin
Marco Vasapollo
 
9054799 dzone-refcard267-kotlin
Zoran Stanimirovic
 
A quick and fast intro to Kotlin
XPeppers
 
Ad

Recently uploaded (20)

PDF
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
PDF
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
PDF
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
PDF
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
PDF
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
PDF
Python basic programing language for automation
DanialHabibi2
 
PPTX
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
PDF
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
PDF
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
PDF
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
PDF
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
PDF
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
PDF
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
PPTX
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
PDF
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
PDF
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
PDF
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
PDF
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
PDF
Blockchain Transactions Explained For Everyone
CIFDAQ
 
PPTX
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
The Builder’s Playbook - 2025 State of AI Report.pdf
jeroen339954
 
NewMind AI - Journal 100 Insights After The 100th Issue
NewMind AI
 
LLMs.txt: Easily Control How AI Crawls Your Site
Keploy
 
Complete JavaScript Notes: From Basics to Advanced Concepts.pdf
haydendavispro
 
"Beyond English: Navigating the Challenges of Building a Ukrainian-language R...
Fwdays
 
Python basic programing language for automation
DanialHabibi2
 
AI Penetration Testing Essentials: A Cybersecurity Guide for 2025
defencerabbit Team
 
Jak MŚP w Europie Środkowo-Wschodniej odnajdują się w świecie AI
dominikamizerska1
 
How Startups Are Growing Faster with App Developers in Australia.pdf
India App Developer
 
Presentation - Vibe Coding The Future of Tech
yanuarsinggih1
 
Newgen 2022-Forrester Newgen TEI_13 05 2022-The-Total-Economic-Impact-Newgen-...
darshakparmar
 
DevBcn - Building 10x Organizations Using Modern Productivity Metrics
Justin Reock
 
Exolore The Essential AI Tools in 2025.pdf
Srinivasan M
 
"Autonomy of LLM Agents: Current State and Future Prospects", Oles` Petriv
Fwdays
 
Reverse Engineering of Security Products: Developing an Advanced Microsoft De...
nwbxhhcyjv
 
Building Real-Time Digital Twins with IBM Maximo & ArcGIS Indoors
Safe Software
 
HCIP-Data Center Facility Deployment V2.0 Training Material (Without Remarks ...
mcastillo49
 
Smart Trailers 2025 Update with History and Overview
Paul Menig
 
Blockchain Transactions Explained For Everyone
CIFDAQ
 
OpenID AuthZEN - Analyst Briefing July 2025
David Brossard
 
Ad

Kotlin cheat sheet by ekito

  • 1. GETTING STARTED Gradle Android In your build.gradle, use gradle setup and the android-kotlin plugins: Gradle Options Compilation tuning in your gradle.properties file: Maven Refer to the documentation online : http://kotlinlang.org/docs/reference/using-maven.html
 BASICS buildscript { ext.kotlin_version = '<version to use>' dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } apply plugin: "kotlin" dependencies { compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" } android { sourceSets { main.java.srcDirs += 'src/main/kotlin' } } apply plugin: 'com.android.application' apply plugin:‘kotlin-android’ apply plugin:‘kotlin-android-extensions’ // if use extensions Kotlin Cheat Sheet Kotlin is an open source statically typed language for the JVM. It can run on Java 6+ and bring smart features to make your code concise and safe. Its high interoperability helps to adopt it very quickly. Official documentation can be found at http://kotlinlang.org/ # Kotlin
 kotlin.incremental=true
 # Android Studio 2.2+
 android.enableBuildCache=true package mypackage 
 import com.package 
 /** A block comment
 */
 // line comment by [email protected] @arnogiu Values & Variables Definition Val represents a constant value & var a mutable value NULL SAFETY & OPTIONAL TYPING Optional typing with <TYPE>? Safe call (?.) or explicit call (!!.) Defining default value with elvis operator (?:) Late variable initialization with lateinit. You can also look at lazy initialized values
 CLASSES A simple Java POJO (Getter, Setter, Constructor) in one line Public Visibility by default All is public by default. Available visibility modifiers are: private, protected, internal, public Data Class By adding data keyword to your class, add toString(), equals(), copy() and exploded data (see destructuring data below) capabilities val a: Int = 1
 val b = 1 // `Int` type is inferred
 val c: Int //Type required when no initializer is provided
 c = 1 // definite assignment var x = 5 // `Int` type is inferred
 x += 1 var stringA: String = "foo"
 stringA = null //Compilation error - stringA is a String (non optional) and can’t have null value
 var stringB: String? = "bar" // stringB is an Optional String
 stringB = null //ok val length = stringB.length // Compilation error - stringB can be null !
 val length = stringB?.length //Value or null - length is type Int? val length = stringB!!.length //Value or explicit throw NullPointerException - length is type Int // set length default value manually
 val length = if (stringB != null) stringB.length else -1
 //or with the Elvis operator
 val length = stringB?.length ?: -1 lateinit var myString : String // lets you define a value later, but is considered as null if not set val myValue : String by lazy { "your value ..." } class User (
 var firstName: String,
 var lastName: String,
 var address: String? = null
 ) by [email protected] @arnogiu
  • 2. Properties Properties can be declared in constructor or class body. You can also limit access to read (get) or write (set) to any property. No Static, use Object ! You can write singleton class, or write companion class methods: Closed Inheritance The : operator, makes inheritance between classes and is allowed by opening it with open modi- fier FUNCTIONS Function can be defined in a class (aka method) or directly in a package. Functions are declared using the fun keyword Default Values Each parameter can have a default value Named Arguments When calling a function, you can freely set the given parameters by its order or by its name: Function Extension Kotlin allows you to define a function to add to an existing Class class User() {//primary empty constructor
 constructor(fn: String) : this() { //secondary constructor must call first one
 firstName = fn
 }
 var firstName: String = ""
 val isFilled: Boolean // read only access property
 get() = !firstName.isEmpty() } // my resource singleton
 object Resource {
 // properties, functions …
 } open class A()
 class B() :A() fun read(b:Array<Byte>, off: Int = 0, len: Int = b.size()) {
 //...
 } fun String.hello(): String = "Hello " + this
 // use the new hello() method
 val hi = "Kotlin !".hello() Kotlin Cheat Sheet read(myBytes, 0, myBytes.length) // old way to call
 reformat(myBytes, len = 128) // using default values & named params by [email protected] @arnogiu Lambda A lambda expression or an anonymous function is a “function literal”, i.e. a function that is not declared, but passed immediately as an expression - A lambda expression is always surrounded by curly braces, - Its parameters (if any) are declared before -> (parameter types may be omitted), - The body goes after -> (when present). Destructuring Data Sometimes it is convenient to destructure an object into a number of variables. Here is the easy way to return two values from a function: Data classes can be accessed with destructured declaration. WHEN - A better flow control when replaces the old C-like switch operator: It can also be used for pattern matching, with expressions, ranges and operators (is, as …) COLLECTIONS Collections are the same as the ones that come with Java. Be aware that Kotlin makes differ- ence between immutable collections and mutables ones. Collection interfaces are immutable. Maps and Arrays can be accessed directly with [] syntax or with range expressions. Various of methods on list/map can be used with lambdas expression : val sum: (Int, Int) -> Int = { x, y -> x + y } fun extractDelimiter(input: String): Pair<String, String> = … val (separator, numberString) = extractDelimiter(input) when (s) {
 1 -> print("x == 1")
 2 -> print("x == 2")
 else -> { // Note the block
 print("x is neither 1 nor 2")
 }
 } // immutable list
 val list = listOf("a", "b", "c","aa")
 list.filter { it.startsWith("a") } // map loop with direct access to key and value
 val map = mapOf("a" to 1, "b" to 2, "c" to 3)
 for ((k, v) in map) {
 println("$k -> $v")
 } // write with mutable map
 map["a"] = "my value" // filter collection items.filter { it % 2 == 0 }
 by [email protected] @arnogiu