K O T L I N
ANDROID
Kotlin for Android dev
100 % interoperable
with Java
Kotlin for Android devs
Developed by JetBrains
KOTLIN
KOTLIN
2010 - Work Started
2011 - Announced
2016 - 1.0 release
2017 - 1.1 release
Official Android First Class Language
Agenda
What is Kotlin ?
Kotlin for Android devs
Why Kotlin ?
Syntax crash course
Features of Kotlin
QnA
Hands-on Session
https://www.tiobe.com/tiobe-index/
Kotlin is climbing up the ladder
• Null references are controlled by the type
system.
• No raw types
• Arrays in Kotlin are invariant
• Kotlin has proper function types, as
opposed to Java’s SAM-conversions
• Use-site variance without wildcards
• Kotlin does not have checked exceptions
Kotlin fixes a series of
issues that Java suffers
from
Checked exceptions
Primitive types that are not classes
Static members
Non-private fields
Wildcard-types
What Java has that Kotlin
does not
KOTLIN & ANDROID
Kotlin can be updated
independently from the OS.
OOP language
with functional
aspects
Modern and
powerful
language
Focuses on
safe concise
and readable
code
Its a statically-typed programming language
What is Kotlin ?
First class tool support
Statically typed programming
language for the JVM,
Android and the browser
What is Kotlin ?
Its a statically-typed programming language
Statically type
What we get by using Java 6/7 + Android -
• Inability to add methods in platform APIs ,
have to use Utils
• NO Lambdas , NO Streams
• NPE - so many of them
What we need
We need modern and smart coding language
Why Kotlin ?
• Not Functional language
• Combines OOP and Functional Programming
features
• Open source
• Targets JVM , Android and even JS
Why Kotlin ?
Kotlin has lots of advantages for #AndroiDev. By using
#Kotlin, my code is simply better for it. - Annyce Davis
I love #Kotlin. It's a breath of fresh air in the #AndroidDev world
- Donn Felker
At work we're just 100% on the #Kotlin train and yes, that
includes #AndroidDev production code! - Huyen Tue Dao
I enjoy writing in #Kotlin because I don't have to use a lot of
#AndroidDev 3rd party libraries - Dmytro Danylyk
#Kotlin enables more concise and understandable code without sacrificing performance
or safety - Dan Lew
Why Kotlin ?
Variables and properties
Syntax
val name: String ="John" //Immutable , its final
var name: String ="John" //Mutable
ex: name= "Johnny"
val name ="John" // Types are auto-inferred
val num: int =10 //Immediate assignment
var personList:List<String> = ArrayList() //Explicit type declaration
Syntax
Immutable
“Anything which will not change is val”
Mutable
“If value will be changed with time use var”
Rule of thumb
Modifiers - Class level
For members declared inside a class :
• Private - member is visible inside the class only.
• Protected - member has the same rules as private but is also available in
subclasses.
• Internal - any member inside the same module can see internal members
• Public - any member who can see the class can see it’s public members.
Default visibility is public
Modifiers - Top level
For declarations declared inside at the top level:
• Private - declaration only visible in the same file.
• Protected - not available as the top level is independent of any class
hierarchy.
• Internal - declaration visible only in the same module
• Public - declaration is visible everywhere
Default visibility is public
// Simple usage
val myValue = a
if (a < b) myValue = b
// As expression
val myValue = if ( a < b) a else b
// when replaces switch operator
when (x) {
1 -> print("First output")
2 -> print("Second output")
else -> {
print(" Nor 1 or 2 ") // This block :)
}
// for loop iterates with iterator
val list = listOf("Game of thrones","Breaking Bad","Gotham")
//while and do ..usual
while (x > 0) {
x--
}
do {
val y= someData()
} while( y!=100)
// Functions in Kotlin are declared using the fun keyword
fun sum (a: Int , b: Int) : Int {
return a + b
}
//or ..single line return
fun sum(a: Int , b: Int , c: Int) = a + b + c
//default values with functions
fun sum(a: Int , b: Int , c: Int , d: Int = 1) = a + b + c + d
Class - big picture
class Person(pName: String) {
var name: String = ""
var age: Int = -1
init {
this.name = pName
}
constructor(pName: String , pAge: Int) : this(pName) {
this.age = pAge
}
fun greet(): String {
return "Hello $name"
}
Class - big picture
class Person(pName: String) {
var name: String = ""
var age: Int = -1
init {
this.name = pName
}
constructor(pName: String , pAge: Int) : this(pName) {
this.age = pAge
}
fun greet(): String {
return "Hello $name"
}
// Instance , we call the constructor as if it were a
//regular function
val person = Person()
val me = Person("Adit")
// Kotlin - has no new keyword
Code
// The full syntax for declaring a property is
private var age:Int =0
get() = field
set(value) {
if(value>0)
field = value
}
internal fun sum(first: Int , second: Int): Int {
return first + second
}
Access modifier Keyword Name
Param name
Param type
Return type
Code
// Full syntax
internal fun sum(first: Int , second: Int): Int {
return first + second
}
// Omit access modifier
fun sum(first: Int , second: Int): Int {
return first + second
}
// Inline return
fun sum(first: Int , second: Int): Int = first + second
// Omit return type
fun sum(first: Int , second: Int) = first + second
// As a type
val sum - { first : Int, second: Int -> first + second }
Higher order functions
• Functions which return a function or take a function
as a parameter
• Used via Lambdas
• Java 6 support
NULL SAFETY
No more
Kotlin’s type system is aimed to eliminate this
forever.
Null Safety
var a: String = "abc"
a = null // compilation error
var b: String? = "abc"
b = null // ok
// what about this ?
val l = a.length // Promise no NPE crash
val l = b.length // error: b can be null
Null Safety
// You could explicitly check if b is null , and handle the options separately
val l = if (b!= null) b.length else -1
// Or ...
val length = b?.length
// Even better
val listWithNulls: List<String?> = listOf("A",null)
for (item in listWithNulls) {
item?.let { println(it)
} // prints A ignores null
Nullability
• In Java, the NullPointerException is one of the biggest headache’s
• Kotlin , ‘null’ is part of the type system
• We can explicitly declare a property , with nullable value
• For each function, we can declare whether it returns a nullable
value
• Goodbye, NullPointerException
Data classes
public class Movie {
private String name;
private String posterImgUrl;
private float rating;
public Movie(String name, String
imageUrl, float rating)
{
this.name = name;
this.posterImgUrl = imageUrl;
this.rating = rating;
}
// Getters and setters
// equals and hashCode
// toString()
}
Data classes
// Just use the keyword 'data' and see the magic
data class Movie(val name: String , val imgUrl:
String , val rating: Float)
val inception = Movie("Inception","http://
inception.com/poster.jpg",4.2)
print(inception.name)
print(inception.imgUrl)
print(inception.rating)
// Pretty print
print(inception.toString())
// Copy object
val inceptionTwo = inception.copy(imgUrl= "http://
imageUrl.com/inception2.png")
Fun tricks
fun evaluateObject(obj: Any): String {
return when(obj){
is String -> "String it is , ahoy !!"
is Int -> "Give me the 8 ball"
else -> "Object is in space"
}
}
fun ImageView.loadUrl(url: String) {
Glide.with(context).load(url).into(this)
}
Extensions
public static boolean isTuesday(Date date) {
return date.getDay() == 2;
}
boolean tuesdayBool =
DateUtils.isTuesday(date);
fun Date.isTuesday(): Boolean {
return getDay() ==2
}
val dateToCheck = Date()
println(date.isTuesday())
Lambdas
myButton.setOnClickListener { navigateToDetail() }
fun apply(one: Int , two: Int , func: (Int, Int) -> Int): Int{
return func(one,two)
}
println(apply(1, 2, { a, b -> a * b }))
println(apply(1, 2, { a, b -> a * 2 - 3 * b }))
Higher order Functions
if (obj instanceOf MyType) {
((MyType)obj).getXValue();
} else {
// Oh no do more
}
Smart Casting
if (obj is MyType) {
obj.getXValue()
} else {
// Oh no do more
}
… and More
• Visibility Modifiers
• Companion Objects
• Nested, Sealed Classes
• Generics
• Coroutines
• Operator overloading
• Exceptions
• Annotations
• Reflection
• and more
… and Even More
• Infix extension methods
• Interfaces
• Interface Delegation
• Property Delegation
• Destructuring
• Safe Singletons
• Init blocks
• Enums
• Multiline Strings
• Tail recursion
CODE
❤ Kotlin
Try Kotlin online
https://goo.gl/z9Hhq6
https://fabiomsr.github.io/from-java-to-kotlin/
QnA
THANK YOU
@aditlal

Kotlin for Android devs

  • 1.
    K O TL I N ANDROID Kotlin for Android dev
  • 2.
    100 % interoperable withJava Kotlin for Android devs Developed by JetBrains KOTLIN
  • 3.
    KOTLIN 2010 - WorkStarted 2011 - Announced 2016 - 1.0 release 2017 - 1.1 release Official Android First Class Language
  • 4.
    Agenda What is Kotlin? Kotlin for Android devs Why Kotlin ? Syntax crash course Features of Kotlin QnA Hands-on Session
  • 5.
  • 7.
    • Null referencesare controlled by the type system. • No raw types • Arrays in Kotlin are invariant • Kotlin has proper function types, as opposed to Java’s SAM-conversions • Use-site variance without wildcards • Kotlin does not have checked exceptions Kotlin fixes a series of issues that Java suffers from
  • 8.
    Checked exceptions Primitive typesthat are not classes Static members Non-private fields Wildcard-types What Java has that Kotlin does not
  • 9.
    KOTLIN & ANDROID Kotlincan be updated independently from the OS.
  • 10.
    OOP language with functional aspects Modernand powerful language Focuses on safe concise and readable code Its a statically-typed programming language What is Kotlin ? First class tool support
  • 11.
    Statically typed programming languagefor the JVM, Android and the browser What is Kotlin ? Its a statically-typed programming language
  • 12.
  • 13.
    What we getby using Java 6/7 + Android - • Inability to add methods in platform APIs , have to use Utils • NO Lambdas , NO Streams • NPE - so many of them What we need We need modern and smart coding language Why Kotlin ?
  • 14.
    • Not Functionallanguage • Combines OOP and Functional Programming features • Open source • Targets JVM , Android and even JS Why Kotlin ?
  • 17.
    Kotlin has lotsof advantages for #AndroiDev. By using #Kotlin, my code is simply better for it. - Annyce Davis I love #Kotlin. It's a breath of fresh air in the #AndroidDev world - Donn Felker At work we're just 100% on the #Kotlin train and yes, that includes #AndroidDev production code! - Huyen Tue Dao I enjoy writing in #Kotlin because I don't have to use a lot of #AndroidDev 3rd party libraries - Dmytro Danylyk #Kotlin enables more concise and understandable code without sacrificing performance or safety - Dan Lew
  • 18.
  • 19.
    Variables and properties Syntax valname: String ="John" //Immutable , its final var name: String ="John" //Mutable ex: name= "Johnny" val name ="John" // Types are auto-inferred val num: int =10 //Immediate assignment var personList:List<String> = ArrayList() //Explicit type declaration
  • 20.
    Syntax Immutable “Anything which willnot change is val” Mutable “If value will be changed with time use var” Rule of thumb
  • 21.
    Modifiers - Classlevel For members declared inside a class : • Private - member is visible inside the class only. • Protected - member has the same rules as private but is also available in subclasses. • Internal - any member inside the same module can see internal members • Public - any member who can see the class can see it’s public members. Default visibility is public
  • 22.
    Modifiers - Toplevel For declarations declared inside at the top level: • Private - declaration only visible in the same file. • Protected - not available as the top level is independent of any class hierarchy. • Internal - declaration visible only in the same module • Public - declaration is visible everywhere Default visibility is public
  • 23.
    // Simple usage valmyValue = a if (a < b) myValue = b // As expression val myValue = if ( a < b) a else b
  • 24.
    // when replacesswitch operator when (x) { 1 -> print("First output") 2 -> print("Second output") else -> { print(" Nor 1 or 2 ") // This block :) }
  • 25.
    // for loopiterates with iterator val list = listOf("Game of thrones","Breaking Bad","Gotham") //while and do ..usual while (x > 0) { x-- } do { val y= someData() } while( y!=100)
  • 26.
    // Functions inKotlin are declared using the fun keyword fun sum (a: Int , b: Int) : Int { return a + b } //or ..single line return fun sum(a: Int , b: Int , c: Int) = a + b + c //default values with functions fun sum(a: Int , b: Int , c: Int , d: Int = 1) = a + b + c + d
  • 27.
    Class - bigpicture class Person(pName: String) { var name: String = "" var age: Int = -1 init { this.name = pName } constructor(pName: String , pAge: Int) : this(pName) { this.age = pAge } fun greet(): String { return "Hello $name" }
  • 28.
    Class - bigpicture class Person(pName: String) { var name: String = "" var age: Int = -1 init { this.name = pName } constructor(pName: String , pAge: Int) : this(pName) { this.age = pAge } fun greet(): String { return "Hello $name" } // Instance , we call the constructor as if it were a //regular function val person = Person() val me = Person("Adit") // Kotlin - has no new keyword
  • 29.
    Code // The fullsyntax for declaring a property is private var age:Int =0 get() = field set(value) { if(value>0) field = value } internal fun sum(first: Int , second: Int): Int { return first + second } Access modifier Keyword Name Param name Param type Return type
  • 30.
    Code // Full syntax internalfun sum(first: Int , second: Int): Int { return first + second } // Omit access modifier fun sum(first: Int , second: Int): Int { return first + second } // Inline return fun sum(first: Int , second: Int): Int = first + second // Omit return type fun sum(first: Int , second: Int) = first + second // As a type val sum - { first : Int, second: Int -> first + second }
  • 31.
    Higher order functions •Functions which return a function or take a function as a parameter • Used via Lambdas • Java 6 support
  • 32.
    NULL SAFETY No more Kotlin’stype system is aimed to eliminate this forever.
  • 33.
    Null Safety var a:String = "abc" a = null // compilation error var b: String? = "abc" b = null // ok // what about this ? val l = a.length // Promise no NPE crash val l = b.length // error: b can be null
  • 34.
    Null Safety // Youcould explicitly check if b is null , and handle the options separately val l = if (b!= null) b.length else -1 // Or ... val length = b?.length // Even better val listWithNulls: List<String?> = listOf("A",null) for (item in listWithNulls) { item?.let { println(it) } // prints A ignores null
  • 35.
    Nullability • In Java,the NullPointerException is one of the biggest headache’s • Kotlin , ‘null’ is part of the type system • We can explicitly declare a property , with nullable value • For each function, we can declare whether it returns a nullable value • Goodbye, NullPointerException
  • 36.
    Data classes public classMovie { private String name; private String posterImgUrl; private float rating; public Movie(String name, String imageUrl, float rating) { this.name = name; this.posterImgUrl = imageUrl; this.rating = rating; } // Getters and setters // equals and hashCode // toString() }
  • 37.
    Data classes // Justuse the keyword 'data' and see the magic data class Movie(val name: String , val imgUrl: String , val rating: Float) val inception = Movie("Inception","http:// inception.com/poster.jpg",4.2) print(inception.name) print(inception.imgUrl) print(inception.rating) // Pretty print print(inception.toString()) // Copy object val inceptionTwo = inception.copy(imgUrl= "http:// imageUrl.com/inception2.png")
  • 38.
    Fun tricks fun evaluateObject(obj:Any): String { return when(obj){ is String -> "String it is , ahoy !!" is Int -> "Give me the 8 ball" else -> "Object is in space" } } fun ImageView.loadUrl(url: String) { Glide.with(context).load(url).into(this) }
  • 39.
    Extensions public static booleanisTuesday(Date date) { return date.getDay() == 2; } boolean tuesdayBool = DateUtils.isTuesday(date); fun Date.isTuesday(): Boolean { return getDay() ==2 } val dateToCheck = Date() println(date.isTuesday())
  • 40.
    Lambdas myButton.setOnClickListener { navigateToDetail()} fun apply(one: Int , two: Int , func: (Int, Int) -> Int): Int{ return func(one,two) } println(apply(1, 2, { a, b -> a * b })) println(apply(1, 2, { a, b -> a * 2 - 3 * b })) Higher order Functions
  • 41.
    if (obj instanceOfMyType) { ((MyType)obj).getXValue(); } else { // Oh no do more } Smart Casting if (obj is MyType) { obj.getXValue() } else { // Oh no do more }
  • 42.
    … and More •Visibility Modifiers • Companion Objects • Nested, Sealed Classes • Generics • Coroutines • Operator overloading • Exceptions • Annotations • Reflection • and more
  • 43.
    … and EvenMore • Infix extension methods • Interfaces • Interface Delegation • Property Delegation • Destructuring • Safe Singletons • Init blocks • Enums • Multiline Strings • Tail recursion
  • 44.
    CODE ❤ Kotlin Try Kotlinonline https://goo.gl/z9Hhq6 https://fabiomsr.github.io/from-java-to-kotlin/
  • 45.
  • 46.