SlideShare a Scribd company logo
Intro to Kotlin
Magda Miu
Intro to Kotlin
Intro to Kotlin
● Properties (val, var)
● String templates
● Null Safety
● Smart Cast
● OOP
● Lambdas
● Collections
● Extensions
● Infix Notation
● Operator Overloading
Agenda
What is Kotlin?
● Statically typed language
● From Jetbrains
● Inspired by Java, Scala, C#, Groovy etc.
● Targets: JVM and Javascript
1.0
Release
1.1
Release
Kotlin is
born
Gradle
Android
Official
Spring
Timeline (Kotlin 1.1.4 is out)
Chart source: https://github.com/jetbrains/kotlin-workshop
Conventions
• The same conventions like on Java
• Uppercase for types
• Lower camelCase for methods and properties
• Semicolons are optional
• Reverse notation for packages
• A file could contain multiple classes
• The folder names not have to match the package name
Development tools
• JDK
• Version 6, 7, 8 and 9
• Kotlin Compiler
• Editor or IDE
• IntelliJ IDEA, Android Studio, NetBeans, Eclipse
Build tools
• Maven
• Gradle
• Kobalt
• Ant
• Command Line
Intro to Kotlin
Basic Data Types
Numbers
Characters
Booleans
Arrays
Strings
Any
Nothing
Properties: val and var
• val is immutable (read-only) and you can only assign a value to them exactly
one time. This is the recommended type to use.
• var is mutable and can be reassigned.
• The type inference is more powerful than Java
• Unit in Kotlin corresponds to the void in Java. Unit is a real class (Singleton)
with only one instance.
• Nothing is a type in Kotlin that represents “a value that never exists”, that
means just “no value at all”.
private final int a = 1;
private int b = 2;
private final int c = 3;
private int d = 4;
public int getA() { return a; }
public int getB() { return b; }
public void setB(int b) { this.b = b; }
public int getC() { return c; }
public int getD() { return d; }
public void setD(int d) { this.d = d; }
val a: Int = 1
var b: Int = 2
val c = 3
var d = 4
Properties: val and var
String templates
• Kotlin supports template expressions
• Simple reference uses $
• Complex references uses ${}
• Raw Strings
class KotlinClass {
fun main(args: Array<String>) {
val first = "Intro to"
val second = "Koltin"
var both = "$first $second"
println("$both has ${both.length}")
println(""""$both" has ${both.length}""")
}
}
/*
1. Menu>Tools>Kotlin>Show Kotlin Bytecode
2. Click on the Decompile button
3. See the java code */
String templates
Public final class JavaClass {
public final void main(@NotNull String[]
args) {
Intrinsics.checkParameterIsNotNull(args,
"args");
String first = "Intro to";
String second = "Koltin";
String both = "" + first + ' ' + second;
String var5 = "" + both + " has " +
both.length();
System.out.println(var5);
var5 = '"' + both + "" has " +
both.length();
System.out.println(var5);
}
}
Null safety
• No more NPEs
• Possible causes for NPE:
• !!
• throw NullPointerException();
• External Java code
• Data inconsistency with regard to initialization
Null safety
• No more NPEs
• Possible causes for NPE:
• !!
• throw NullPointerException();
• External Java code
• Data inconsistency with regard to initialization
class KotlinClass {
val notNullString: String = null //error!
val nullableString: String? = null
//condition checks
var theString: String? = "abc"
val length1 = if (theString != null)
theString.length else -1
//safe calls
val length2 = theString?.length
//elvis operator
val length3 = theString?.length ?: -1
//use !!
val length4 = theString!!.length
//safe casts
val aInt: Int? = theString as? Int
}
Class
• Many classes in the same file
• Classes and methods are final by default. Use open for extensibility.
• Only properties(public by default) and functions(fun)
• No new keyword on instantiation
• lateinit for properties (not null) and they should be mutable
• init block is equal with the constructor in Java
• inner keyword to be able to access members of the surrounding class
class KotlinClass(var name: String) {
lateinit var gdg: GDGPitesti
val language: String
init {
language = "Kotlin"
}
fun initializeName (name: String) {
gdg = GDGPitesti(name)
}
inner class GDGPitesti(val text: String)
fun sayItFromGDG(): String = "${gdg.text}
$name $language"
}
fun main(args: Array<String>) {
var a = KotlinClass("loves")
a.initializeName("GDG Pitesti")
print(a.sayItFromGDG())//GDG Pitesti loves Kotlin
}
Class
public final class JavaClass {
@NotNull
public KotlinClass.GDGPitesti gdg;
@NotNull
private final String language;
@NotNull
private String name;
@NotNull
public final KotlinClass.GDGPitesti getGdg() {
KotlinClass.GDGPitesti var10000 = this.gdg;
if(this.gdg == null) {
Intrinsics.throwUninitializedPropertyAccessExcept
ion("gdg");
}
return var10000;
}
…
Data Class
• data class contains:
• properties
• equals
• hashCode
• toString
• copy
• component (Destructuring Declarations)
data class Coordinate(var lat: Double, var lon:
Double)
fun main(args: Array<String>) {
val city1 = Coordinate(24.5, 48.5)
//copy
val city2 = city1.copy(lat = 25.7)
//component
val (theLat, theLon) = city2
println(city1)
println(city2)
println(theLat)
println(theLon)
}
Data Class
public final class CoordinateJava {
private double lat;
private double lon;
public final double getLat() {
return this.lat;
}
public final void setLat(double var1) {
this.lat = var1;
}
public final double getLon() {
return this.lon;
}
public final void setLon(double var1) {
this.lon = var1;
}
….
Interface
• Could contain abstract methods and/or properties
• They need to be initialized in the implementing class in order to respect the
contract of the interface
• override keyword is mandatory
• A property declared in an interface can either be abstract, or it can provide
implementations for accessors.
interface GDG {
val name: String
fun getCity(): String
}
class GDGPitesti: GDG{
override val name: String = "GDG"
override fun getCity(): String = "$name
Pitesti"
}
fun main(args: Array<String>) {
println(GDGPitesti().getCity())
}
Interface
Object
• The object keyword creates singleton in Kotlin
• An object declaration inside a class can be marked with the companion keyword
• Members of the companion object can be called by using simply the class name
as the qualifier (like static on Java)
• The name of the companion object can be omitted, in which case the name
Companion will be used
object SingletonClass {
fun getHello(): String = "Hello Singleton"
}
class CompaniedClass(val str: String) {
companion object Printer {
fun getHello(): String = "Hello Companion"
}
}
class NoNameCompaniedClass(val str: String) {
companion object {
fun getHello(): String = "Hello No Name
Companion"
}
}
fun main(args: Array<String>) {
SingletonClass.getHello() // Hello Singleton
CompaniedClass.getHello() // Hello Companion
NoNameCompaniedClass.getHello() // Hello No
Name Companion
}
Object
fun main(args: Array<String>) {
val a = 4; val b = 7
val max = if (a > b) {
println("$a is grater than $b"); a
} else {
println("$b is grater than $a"); b
}
println(max)
println(describe("GDG"))
for (i in 1..10 step 2) {
print("$i ")
}}
fun describe(obj: Any): String =
when (obj) {
1 -> "One"
"Hello" -> "Greeting"
is Long -> "Long"
!is String -> "Not a string"
else -> "Awesome"
}
It’s all about expressions...
Collections and Lambdas
• Kotlin distinguishes between
mutable and immutable
collections
• The supported operations on
Collections are: map,
flatMap, forEach, fold,
reduce, filter, zip etc.
• to is in infix function
fun main(args: Array<String>) {
listOf(1, 2, 3); mutableListOf("a", "b", "c")
setOf(1, 2, 3); mutableSetOf("a", "b", "c")
mapOf(1 to "a", 2 to "b", 3 to "c")
mutableMapOf("a" to 1, "b" to 2, "c" to 3)
val aList = listOf(1, 2, 4)
println(aList.map { elem ->
elem + 1
})
println(aList)
println(aList.filter { it != 1 })
fun sum(a: Int, b: Int) = a + b
println(aList.reduce(::sum))
}
Extensions functions
• Add operators to the classes by
using the operator
• Create infix functions with the
infix keyword
• Extension functions are normal
static methods bearing no
connection with the class they are
extending, other than taking an
instance of this class as a
parameters
fun main(args: Array<String>) {
val x = "Kotlin"
println(x.last())
val m1 = Matrix(1, 2, 3, 4)
val m2 = Matrix(1, 1, 1, 1)
val m3 = m1 + m2
println("${m3.a} ${m3.b} ${m3.c} ${m3.d}")
}
fun String.last(): Char {
return this[length - 1]
}
class Matrix(val a: Int, val b: Int, val c: Int,
val d: Int) {
operator fun plus(matrix: Matrix): Matrix {
return Matrix(a + matrix.a, b + matrix.b,
c + matrix.c, d + matrix.d)
}
}
Questions?
Resources
● Images source: buzzfeed.com
● http://jussi.hallila.com/Kollections/
● https://try.kotlinlang.org
● https://kotlinlang.org/docs/books.html

More Related Content

PDF
Kotlin boost yourproductivity
PDF
Taking Kotlin to production, Seriously
PDF
Coding for Android on steroids with Kotlin
PPTX
Introduction to kotlin + spring boot demo
PDF
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
PDF
Introduction to kotlin
PPT
The Kotlin Programming Language
PDF
2017: Kotlin - now more than ever
Kotlin boost yourproductivity
Taking Kotlin to production, Seriously
Coding for Android on steroids with Kotlin
Introduction to kotlin + spring boot demo
Introduction to kotlin for android app development gdg ahmedabad dev fest 2017
Introduction to kotlin
The Kotlin Programming Language
2017: Kotlin - now more than ever

What's hot (19)

PDF
Kotlin, smarter development for the jvm
PDF
No excuses, switch to kotlin
PPTX
Kotlin as a Better Java
PDF
Develop your next app with kotlin @ AndroidMakersFr 2017
PDF
BangaloreJUG introduction to kotlin
PDF
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
PDF
Kotlin hands on - MorningTech ekito 2017
PPTX
Fall in love with Kotlin
PDF
Kotlin: Challenges in JVM language design
PDF
Building microservices with Kotlin
PDF
Kotlin for Android - Vali Iorgu - mRready
PDF
Kotlin advanced - language reference for android developers
PDF
Kotlin in action
PDF
Swift and Kotlin Presentation
PDF
Summer of Tech 2017 - Kotlin/Android bootcamp
PDF
Kotlin Developer Starter in Android projects
PDF
Kotlin cheat sheet by ekito
PDF
Kotlin - Better Java
PDF
A quick and fast intro to Kotlin
Kotlin, smarter development for the jvm
No excuses, switch to kotlin
Kotlin as a Better Java
Develop your next app with kotlin @ AndroidMakersFr 2017
BangaloreJUG introduction to kotlin
Kotlin - The Swiss army knife of programming languages - Visma Mobile Meet-up...
Kotlin hands on - MorningTech ekito 2017
Fall in love with Kotlin
Kotlin: Challenges in JVM language design
Building microservices with Kotlin
Kotlin for Android - Vali Iorgu - mRready
Kotlin advanced - language reference for android developers
Kotlin in action
Swift and Kotlin Presentation
Summer of Tech 2017 - Kotlin/Android bootcamp
Kotlin Developer Starter in Android projects
Kotlin cheat sheet by ekito
Kotlin - Better Java
A quick and fast intro to Kotlin
Ad

Similar to Intro to Kotlin (20)

PDF
Privet Kotlin (Windy City DevFest)
PPTX
K is for Kotlin
PDF
Exploring Kotlin
PDF
Little Helpers for Android Development with Kotlin
PDF
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
PDF
Kotlin: A pragmatic language by JetBrains
PPTX
KotlinForJavaDevelopers-UJUG.pptx
PDF
Kotlin @ Devoxx 2011
PDF
Kotlin Slides from Devoxx 2011
PDF
Kotlin: forse è la volta buona (Trento)
PDF
9054799 dzone-refcard267-kotlin
PDF
Kotlin intro
PDF
Kotlin/Everywhere GDG Bhubaneswar 2019
PDF
2 kotlin vs. java: what java has that kotlin does not
PDF
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
PPTX
Building Mobile Apps with Android
PDF
Having Fun with Kotlin Android - DILo Surabaya
PPTX
Introduction to Kotlin
PDF
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
PPTX
Hello kotlin | An Event by DSC Unideb
Privet Kotlin (Windy City DevFest)
K is for Kotlin
Exploring Kotlin
Little Helpers for Android Development with Kotlin
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
Kotlin: A pragmatic language by JetBrains
KotlinForJavaDevelopers-UJUG.pptx
Kotlin @ Devoxx 2011
Kotlin Slides from Devoxx 2011
Kotlin: forse è la volta buona (Trento)
9054799 dzone-refcard267-kotlin
Kotlin intro
Kotlin/Everywhere GDG Bhubaneswar 2019
2 kotlin vs. java: what java has that kotlin does not
2022 May - Shoulders of Giants - Amsterdam - Kotlin Dev Day.pdf
Building Mobile Apps with Android
Having Fun with Kotlin Android - DILo Surabaya
Introduction to Kotlin
eMan Dev Meetup: Kotlin - A Language we should know it exists (part 02/03) 18...
Hello kotlin | An Event by DSC Unideb
Ad

Recently uploaded (20)

PDF
Spectral efficient network and resource selection model in 5G networks
PDF
MIND Revenue Release Quarter 2 2025 Press Release
PDF
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
PDF
Unlocking AI with Model Context Protocol (MCP)
PDF
Approach and Philosophy of On baking technology
PPTX
Digital-Transformation-Roadmap-for-Companies.pptx
PPT
Teaching material agriculture food technology
PPTX
Understanding_Digital_Forensics_Presentation.pptx
PPTX
Cloud computing and distributed systems.
PDF
Electronic commerce courselecture one. Pdf
PDF
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
DOCX
The AUB Centre for AI in Media Proposal.docx
PDF
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
PDF
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
PDF
Review of recent advances in non-invasive hemoglobin estimation
PDF
Encapsulation theory and applications.pdf
PDF
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
PDF
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
PPTX
sap open course for s4hana steps from ECC to s4
PDF
Empathic Computing: Creating Shared Understanding
Spectral efficient network and resource selection model in 5G networks
MIND Revenue Release Quarter 2 2025 Press Release
Profit Center Accounting in SAP S/4HANA, S4F28 Col11
Unlocking AI with Model Context Protocol (MCP)
Approach and Philosophy of On baking technology
Digital-Transformation-Roadmap-for-Companies.pptx
Teaching material agriculture food technology
Understanding_Digital_Forensics_Presentation.pptx
Cloud computing and distributed systems.
Electronic commerce courselecture one. Pdf
Build a system with the filesystem maintained by OSTree @ COSCUP 2025
The AUB Centre for AI in Media Proposal.docx
How UI/UX Design Impacts User Retention in Mobile Apps.pdf
Optimiser vos workloads AI/ML sur Amazon EC2 et AWS Graviton
Review of recent advances in non-invasive hemoglobin estimation
Encapsulation theory and applications.pdf
Architecting across the Boundaries of two Complex Domains - Healthcare & Tech...
TokAI - TikTok AI Agent : The First AI Application That Analyzes 10,000+ Vira...
sap open course for s4hana steps from ECC to s4
Empathic Computing: Creating Shared Understanding

Intro to Kotlin

  • 4. ● Properties (val, var) ● String templates ● Null Safety ● Smart Cast ● OOP ● Lambdas ● Collections ● Extensions ● Infix Notation ● Operator Overloading Agenda
  • 5. What is Kotlin? ● Statically typed language ● From Jetbrains ● Inspired by Java, Scala, C#, Groovy etc. ● Targets: JVM and Javascript
  • 6. 1.0 Release 1.1 Release Kotlin is born Gradle Android Official Spring Timeline (Kotlin 1.1.4 is out) Chart source: https://github.com/jetbrains/kotlin-workshop
  • 7. Conventions • The same conventions like on Java • Uppercase for types • Lower camelCase for methods and properties • Semicolons are optional • Reverse notation for packages • A file could contain multiple classes • The folder names not have to match the package name
  • 8. Development tools • JDK • Version 6, 7, 8 and 9 • Kotlin Compiler • Editor or IDE • IntelliJ IDEA, Android Studio, NetBeans, Eclipse
  • 9. Build tools • Maven • Gradle • Kobalt • Ant • Command Line
  • 12. Properties: val and var • val is immutable (read-only) and you can only assign a value to them exactly one time. This is the recommended type to use. • var is mutable and can be reassigned. • The type inference is more powerful than Java • Unit in Kotlin corresponds to the void in Java. Unit is a real class (Singleton) with only one instance. • Nothing is a type in Kotlin that represents “a value that never exists”, that means just “no value at all”.
  • 13. private final int a = 1; private int b = 2; private final int c = 3; private int d = 4; public int getA() { return a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public int getD() { return d; } public void setD(int d) { this.d = d; } val a: Int = 1 var b: Int = 2 val c = 3 var d = 4 Properties: val and var
  • 14. String templates • Kotlin supports template expressions • Simple reference uses $ • Complex references uses ${} • Raw Strings
  • 15. class KotlinClass { fun main(args: Array<String>) { val first = "Intro to" val second = "Koltin" var both = "$first $second" println("$both has ${both.length}") println(""""$both" has ${both.length}""") } } /* 1. Menu>Tools>Kotlin>Show Kotlin Bytecode 2. Click on the Decompile button 3. See the java code */ String templates Public final class JavaClass { public final void main(@NotNull String[] args) { Intrinsics.checkParameterIsNotNull(args, "args"); String first = "Intro to"; String second = "Koltin"; String both = "" + first + ' ' + second; String var5 = "" + both + " has " + both.length(); System.out.println(var5); var5 = '"' + both + "" has " + both.length(); System.out.println(var5); } }
  • 16. Null safety • No more NPEs • Possible causes for NPE: • !! • throw NullPointerException(); • External Java code • Data inconsistency with regard to initialization
  • 17. Null safety • No more NPEs • Possible causes for NPE: • !! • throw NullPointerException(); • External Java code • Data inconsistency with regard to initialization class KotlinClass { val notNullString: String = null //error! val nullableString: String? = null //condition checks var theString: String? = "abc" val length1 = if (theString != null) theString.length else -1 //safe calls val length2 = theString?.length //elvis operator val length3 = theString?.length ?: -1 //use !! val length4 = theString!!.length //safe casts val aInt: Int? = theString as? Int }
  • 18. Class • Many classes in the same file • Classes and methods are final by default. Use open for extensibility. • Only properties(public by default) and functions(fun) • No new keyword on instantiation • lateinit for properties (not null) and they should be mutable • init block is equal with the constructor in Java • inner keyword to be able to access members of the surrounding class
  • 19. class KotlinClass(var name: String) { lateinit var gdg: GDGPitesti val language: String init { language = "Kotlin" } fun initializeName (name: String) { gdg = GDGPitesti(name) } inner class GDGPitesti(val text: String) fun sayItFromGDG(): String = "${gdg.text} $name $language" } fun main(args: Array<String>) { var a = KotlinClass("loves") a.initializeName("GDG Pitesti") print(a.sayItFromGDG())//GDG Pitesti loves Kotlin } Class public final class JavaClass { @NotNull public KotlinClass.GDGPitesti gdg; @NotNull private final String language; @NotNull private String name; @NotNull public final KotlinClass.GDGPitesti getGdg() { KotlinClass.GDGPitesti var10000 = this.gdg; if(this.gdg == null) { Intrinsics.throwUninitializedPropertyAccessExcept ion("gdg"); } return var10000; } …
  • 20. Data Class • data class contains: • properties • equals • hashCode • toString • copy • component (Destructuring Declarations)
  • 21. data class Coordinate(var lat: Double, var lon: Double) fun main(args: Array<String>) { val city1 = Coordinate(24.5, 48.5) //copy val city2 = city1.copy(lat = 25.7) //component val (theLat, theLon) = city2 println(city1) println(city2) println(theLat) println(theLon) } Data Class public final class CoordinateJava { private double lat; private double lon; public final double getLat() { return this.lat; } public final void setLat(double var1) { this.lat = var1; } public final double getLon() { return this.lon; } public final void setLon(double var1) { this.lon = var1; } ….
  • 22. Interface • Could contain abstract methods and/or properties • They need to be initialized in the implementing class in order to respect the contract of the interface • override keyword is mandatory • A property declared in an interface can either be abstract, or it can provide implementations for accessors.
  • 23. interface GDG { val name: String fun getCity(): String } class GDGPitesti: GDG{ override val name: String = "GDG" override fun getCity(): String = "$name Pitesti" } fun main(args: Array<String>) { println(GDGPitesti().getCity()) } Interface
  • 24. Object • The object keyword creates singleton in Kotlin • An object declaration inside a class can be marked with the companion keyword • Members of the companion object can be called by using simply the class name as the qualifier (like static on Java) • The name of the companion object can be omitted, in which case the name Companion will be used
  • 25. object SingletonClass { fun getHello(): String = "Hello Singleton" } class CompaniedClass(val str: String) { companion object Printer { fun getHello(): String = "Hello Companion" } } class NoNameCompaniedClass(val str: String) { companion object { fun getHello(): String = "Hello No Name Companion" } } fun main(args: Array<String>) { SingletonClass.getHello() // Hello Singleton CompaniedClass.getHello() // Hello Companion NoNameCompaniedClass.getHello() // Hello No Name Companion } Object
  • 26. fun main(args: Array<String>) { val a = 4; val b = 7 val max = if (a > b) { println("$a is grater than $b"); a } else { println("$b is grater than $a"); b } println(max) println(describe("GDG")) for (i in 1..10 step 2) { print("$i ") }} fun describe(obj: Any): String = when (obj) { 1 -> "One" "Hello" -> "Greeting" is Long -> "Long" !is String -> "Not a string" else -> "Awesome" } It’s all about expressions...
  • 27. Collections and Lambdas • Kotlin distinguishes between mutable and immutable collections • The supported operations on Collections are: map, flatMap, forEach, fold, reduce, filter, zip etc. • to is in infix function fun main(args: Array<String>) { listOf(1, 2, 3); mutableListOf("a", "b", "c") setOf(1, 2, 3); mutableSetOf("a", "b", "c") mapOf(1 to "a", 2 to "b", 3 to "c") mutableMapOf("a" to 1, "b" to 2, "c" to 3) val aList = listOf(1, 2, 4) println(aList.map { elem -> elem + 1 }) println(aList) println(aList.filter { it != 1 }) fun sum(a: Int, b: Int) = a + b println(aList.reduce(::sum)) }
  • 28. Extensions functions • Add operators to the classes by using the operator • Create infix functions with the infix keyword • Extension functions are normal static methods bearing no connection with the class they are extending, other than taking an instance of this class as a parameters fun main(args: Array<String>) { val x = "Kotlin" println(x.last()) val m1 = Matrix(1, 2, 3, 4) val m2 = Matrix(1, 1, 1, 1) val m3 = m1 + m2 println("${m3.a} ${m3.b} ${m3.c} ${m3.d}") } fun String.last(): Char { return this[length - 1] } class Matrix(val a: Int, val b: Int, val c: Int, val d: Int) { operator fun plus(matrix: Matrix): Matrix { return Matrix(a + matrix.a, b + matrix.b, c + matrix.c, d + matrix.d) } }
  • 30. Resources ● Images source: buzzfeed.com ● http://jussi.hallila.com/Kollections/ ● https://try.kotlinlang.org ● https://kotlinlang.org/docs/books.html