Kotlin for Android devs

46
KOTLIN ANDROID Kotlin for Android dev

Transcript of Kotlin for Android devs

K O T L I N

ANDROID

Kotlin for Android dev

100 % interoperable with Java

Kotlin for Android devs

Developed by JetBrains

KOTLIN

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

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 needWe 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 propertiesSyntax

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 functionval person = Person()val me = Person("Adit")

// Kotlin - has no new keyword

Code// The full syntax for declaring a property is

private var age:Int =0get() = fieldset(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 syntaxinternal fun sum(first: Int , second: Int): Int { return first + second}

// Omit access modifierfun sum(first: Int , second: Int): Int { return first + second}

// Inline returnfun sum(first: Int , second: Int): Int = first + second

// Omit return typefun sum(first: Int , second: Int) = first + second

// As a typeval 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 separatelyval 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 printprint(inception.toString())

// Copy objectval 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