SlideShare a Scribd company logo
1 of 2
Download to read offline
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

Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyHaim Yadid
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017Hardik Trivedi
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Tudor Dragan
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaVasil Remeniuk
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin PresentationAndrzej Sitek
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoMuhammad Abdullah
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivitynklmish
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinKai Koenig
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan s.r.o.
 
Coding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinCoding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinKai Koenig
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devsAdit Lal
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?Tomasz Wrobel
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Languageintelliyole
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to KotlinMagda Miu
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?Squareboat
 

What's hot (19)

Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Taking Kotlin to production, Seriously
Taking Kotlin to production, SeriouslyTaking Kotlin to production, Seriously
Taking Kotlin to production, Seriously
 
Kotlin
KotlinKotlin
Kotlin
 
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017Introduction to kotlin for android app development   gdg ahmedabad dev fest 2017
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
 
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
 
The Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana IsakovaThe Kotlin Programming Language, Svetlana Isakova
The Kotlin Programming Language, Svetlana Isakova
 
Swift and Kotlin Presentation
Swift and Kotlin PresentationSwift and Kotlin Presentation
Swift and Kotlin Presentation
 
Introduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demoIntroduction to kotlin + spring boot demo
Introduction to kotlin + spring boot demo
 
Kotlin boost yourproductivity
Kotlin boost yourproductivityKotlin boost yourproductivity
Kotlin boost yourproductivity
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with Kotlin
 
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
 
Android antipatterns
Android antipatternsAndroid antipatterns
Android antipatterns
 
Kotlin - Better Java
Kotlin - Better JavaKotlin - Better Java
Kotlin - Better Java
 
Coding for Android on steroids with Kotlin
Coding for Android on steroids with KotlinCoding for Android on steroids with Kotlin
Coding for Android on steroids with Kotlin
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
 
(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?(How) can we benefit from adopting scala?
(How) can we benefit from adopting scala?
 
The Kotlin Programming Language
The Kotlin Programming LanguageThe Kotlin Programming Language
The Kotlin Programming Language
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 

Similar to Kotlin cheat sheet by ekito

Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехБоремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехСбертех | SberTech
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does notSergey Bandysik
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin XPeppers
 
Kotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrainsKotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrainsJigar Gosar
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance Coder Tech
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Mohamed Nabil, MSc.
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for KotlinTechMagic
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Cody Engel
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developersMohamed Wael
 
Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers STX Next
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answersAkash Gawali
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And AnswerJagan Mohan Bishoyi
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answerlavparmar007
 

Similar to Kotlin cheat sheet by ekito (20)

Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехБоремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
 
2 kotlin vs. java: what java has that kotlin does not
2  kotlin vs. java: what java has that kotlin does not2  kotlin vs. java: what java has that kotlin does not
2 kotlin vs. java: what java has that kotlin does not
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
A quick and fast intro to Kotlin
A quick and fast intro to Kotlin A quick and fast intro to Kotlin
A quick and fast intro to Kotlin
 
Kotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrainsKotlin: A pragmatic language by JetBrains
Kotlin: A pragmatic language by JetBrains
 
Scala for curious
Scala for curiousScala for curious
Scala for curious
 
Kotlin- Basic to Advance
Kotlin- Basic to Advance Kotlin- Basic to Advance
Kotlin- Basic to Advance
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
Lecture 5
Lecture 5Lecture 5
Lecture 5
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
Java session4
Java session4Java session4
Java session4
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
Introduction to Kotlin for Android developers
Introduction to Kotlin for Android developersIntroduction to Kotlin for Android developers
Introduction to Kotlin for Android developers
 
Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers
 
Introduction to Kotlin
Introduction to KotlinIntroduction to Kotlin
Introduction to Kotlin
 
Swift, swiftly
Swift, swiftlySwift, swiftly
Swift, swiftly
 
Scala fundamentals
Scala fundamentalsScala fundamentals
Scala fundamentals
 
1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers1183 c-interview-questions-and-answers
1183 c-interview-questions-and-answers
 
C++ Interview Question And Answer
C++ Interview Question And AnswerC++ Interview Question And Answer
C++ Interview Question And Answer
 
C++ questions And Answer
C++ questions And AnswerC++ questions And Answer
C++ questions And Answer
 

Recently uploaded

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesZilliz
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostZilliz
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticscarlostorres15106
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii SoldatenkoFwdays
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024The Digital Insurer
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Manik S Magar
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...Fwdays
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfAlex Barbosa Coqueiro
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek SchlawackFwdays
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

Vector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector DatabasesVector Databases 101 - An introduction to the world of Vector Databases
Vector Databases 101 - An introduction to the world of Vector Databases
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage CostLeverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
Leverage Zilliz Serverless - Up to 50X Saving for Your Vector Storage Cost
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmaticsKotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
Kotlin Multiplatform & Compose Multiplatform - Starter kit for pragmatics
 
"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko"Debugging python applications inside k8s environment", Andrii Soldatenko
"Debugging python applications inside k8s environment", Andrii Soldatenko
 
My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024My INSURER PTE LTD - Insurtech Innovation Award 2024
My INSURER PTE LTD - Insurtech Innovation Award 2024
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!Anypoint Exchange: It’s Not Just a Repo!
Anypoint Exchange: It’s Not Just a Repo!
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks..."LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
"LLMs for Python Engineers: Advanced Data Analysis and Semantic Kernel",Oleks...
 
Unraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdfUnraveling Multimodality with Large Language Models.pdf
Unraveling Multimodality with Large Language Models.pdf
 
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
"Subclassing and Composition – A Pythonic Tour of Trade-Offs", Hynek Schlawack
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 

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 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
  • 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 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