SlideShare une entreprise Scribd logo
1  sur  46
Télécharger pour lire hors ligne
Having fun
with Kotlin – Android
Eko Suhariyadi
What this presentation cover
●
Kotlin introduction
●
What we can achieve by using Kotlin for Android
Development
What is Kotlin
●
Brand new programming language by JetBrains which targeting Java Platform,
open sourced and free to use
●
Kotlin is concise, safe, pragmatic, and focused on interoperability with Java code
– Works great with all existing Java libraries and frameworks
– Runs with same level performance as Java
●
Can be used for server-side development, Android apps, Desktop apps, and
much more. Anywhere Java runs
●
It’s statically typed programming language
●
Functional and Object Oriented
– First-class functions
– Immutability
– No side-effects
A bit History of Kotlin
●
Internal project of JetBrains unveiled in July 2011 after a year of development
– Seeking for language for future development
– Scala is great, but compile time and interoperability is obvious deficiency
●
Open sourced on February 2012 under Apache 2 license
●
First v1.0 released on February 15, 2016
– It takes 6 years for the first stable release
●
v1.1 just released on March 1, 2017
●
Named after Kotlin Island, near St. Petersburg, Russia.
Where most JetBrains’ Kotlin development team work
●
“Some part” of the language design is based on “Effective Java” book by
Joshua Bloch
Fun Facts?
●
C takes 1 years to first stable release
●
C++ takes 4 years
●
Java takes 4 years
●
Python takes 3 years
●
JavaScript only takes 10 days :-)
#DuaMingguJadi
Installation
●
Recommended way
– Intellij IDEA or Android Studio plugin
●
Standalone compiler
– via SDKMAN (sdkman.io)
– sdk install kotlin
Why Kotlin
●
(Android) Stuck on Java 6
– No streams
– No lambda, method references
●
Jack and Jill still on experimental
(Java 8 support for Android)
– No try-with-resources
Why Kotlin
●
(Android) Stuck on Java 6
– No streams Use RxJava
– No lambda, method references
●
Jack and Jill still on experimental
(Java 8 support for Android)
– No try-with-resources
Why Kotlin
●
(Android) Stuck on Java 6
– No streams Use RxJava
– No lambda, method references Use Retrolambda
●
Jack and Jill still on experimental
(Java 8 support for Android)
– No try-with-resources
Why Kotlin
●
(Android) Stuck on Java 6
– No streams Use RxJava
– No lambda, method references Use Retrolambda
●
Jack and Jill still on experimental
(Java 8 support for Android)
– No try-with-resources minSdkVersion = 19 or Use
Retrolambda
Why Kotlin
●
(Android) Stuck on Java 6
●
Inability to add methods to platform types in Java
– Achieved via Util class
●
Nullability problems (*NullPointerException) in Java
●
General verbosity / boilerplate code in Java
– Too much code to achieve minimal jobs
Taste of Kotlin
data class Person(val name: String,
val age: Int? = null)
fun main(args: Array<String>) {
val persons = listOf(Person("John Doe"),
Person("Logan", age = 49))
val oldest = persons.maxBy { it.age ?: 0 }
println("The oldest is $oldest")
}
// The oldest is Person(name=Logan, age=49)
Bye bye semicolon ;
Type after variable
Nullability and default value
Lambda expression
String template/interpolation
Data class
Named parameter
No “new”
Taste of Kotlin
●
Property declaration
– val (*value) for immutable property, ie once initialized
can’t be changed
– var (*variable) for mutable property, can be reassign
●
“fun” keyword to declare method/function
– So literally we are having fun when code in Kotlin
Taste of Kotlin
fun someFunction(): Unit { // functions always have return value
var say: String = "Kotlin is pragmatic language"
say = "also safe and concise"
val hello: String = "Domo Arigatou Mr. Roboto"
hello = "updated hello" // compile time error
return Unit
}
fun sum(x: Int, y: Int): Int {
return x + y
}
Taste of Kotlin
fun someFunction() {
var say = "Kotlin is pragmatic language"
say = "also safe and concise"
val hello = "Domo Arigatou Mr. Roboto"
// hello = "updated hello"
}
fun sum(x: Int, y: Int) = x + y // one liner
// Type inference
// compiler infer the type of properties without explicit declaration
1. Null Safety
data class Contact(val name: String, var email: String? = null) {
constructor(name: String) : this(name, null)
}
fun main(args: Array<String>) {
val eko = Contact(email = "eko.suhariyadi@gmail.com",
name = "Eko Suhariyadi")
eko.name = null // compile error
eko.email = null // ok
}
Working with null
val eko = Contact("Eko Suhariyadi")
// if email is null return other value,
// with elvis operator ?:
val email: String = eko.email ?: "Have no email"
// cascading null safety
val emailStrSize = eko.email?.length
// safe scoping
eko.email?.let {
// send email
// only executed if email is not null
}
2. Conciseness
Java:
view.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// do something
}
});
2. Conciseness
Kotlin:
view.setOnClickListener {
// do something
}
view.setOnClickListener { view: View ->
// do something with the view
}
view.setOnClickListener { view ->
// do something with the view
}
3. Data Class
●
Write POJO class in Java is quite verbose
– overloading constructor?
– getter and setter
– toString
– hashCode and equals
●
IDE could help for code generation
●
Or by using libraries such as Google’s AutoValue
3. Data Classpublic class Todo {
private String description;
private Long createdAt;
private boolean done;
public Todo(String description, Long createdAt, boolean done) {
this.description = description;
this.createdAt = createdAt;
this.done = done;
}
// ...
3. Data Classpublic class Todo {
private String description;
private Long createdAt;
private boolean done;
public Todo(String description, Long createdAt, boolean done) {
this.description = description;
this.createdAt = createdAt;
this.done = done;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Long createdAt) {
this.createdAt = createdAt;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
// ...
3. Data Classpublic class Todo {
private String description;
private Long createdAt;
private boolean done;
public Todo(String description, Long createdAt, boolean done) {
this.description = description;
this.createdAt = createdAt;
this.done = done;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Long getCreatedAt() {
return createdAt;
}
public void setCreatedAt(Long createdAt) {
this.createdAt = createdAt;
}
public boolean isDone() {
return done;
}
public void setDone(boolean done) {
this.done = done;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Todo todo = (Todo) o;
if (done != todo.done) return false;
return description != null ? description.equals(todo.description) : todo.description == null && (createdAt != null ? createdAt.equals(todo.createdAt) : todo.createdAt ==
null);
}
@Override
public int hashCode() {
int result = description != null ? description.hashCode() : 0;
result = 31 * result + (createdAt != null ? createdAt.hashCode() : 0);
result = 31 * result + (done ? 1 : 0);
return result;
}
@Override
public String toString() {
return "Todo{" +
"description='" + description + ''' +
", createdAt=" + createdAt +
", done=" + done +
'}';
}
}
3. Data Class
data class TodoKotlin(var description: String,
var createdAt: Long,
var done: Boolean = false)
→ javap TodoKotlin.class
public final class com.codangcoding.havingfunkotlin.TodoKotlin {
public final java.lang.String getDescription();
public final void setDescription(java.lang.String);
public final long getCreatedAt();
public final void setCreatedAt(long);
public final boolean getDone();
public final void setDone(boolean);
public com.codangcoding.havingfunkotlin.TodoKotlin(java.lang.String, long, boolean);
public com.codangcoding.havingfunkotlin.TodoKotlin(java.lang.String, long, boolean, int,
kotlin.jvm.internal.DefaultConstructorMarker);
public final java.lang.String component1();
public final long component2();
public final boolean component3();
public final com.codangcoding.havingfunkotlin.TodoKotlin copy(java.lang.String, long, boolean);
public static com.codangcoding.havingfunkotlin.TodoKotlin copy$default(com.codangcoding.havingfunkotlin.TodoKotlin,
java.lang.String, long, boolean, int, java.lang.Object);
public java.lang.String toString();
public int hashCode();
public boolean equals(java.lang.Object);
}
3. Data Class
●
Kotlin data class generate compiled code almost same with Java
POJO
●
But with extra method
– component(N) for destructure
– copy for “prototype pattern”
val todo = TodoKotlin("Sample TODO", System.currentTimeMillis())
val (description, createdAt, done) = todo // destructure
println("$description, $createdAt, $done")
// need to destruct description and done only
val (desc, _, finished) = todo
println("$desc, $finished")
// create new object by cloning from other
val copiedTodo = todo.copy(
description = "Copy from Sample TODO", done = true)
println("""|
|$todo
|vs
|$copiedTodo""".trimMargin())
4. Extensions Functions
●
Ability to add functions or properties to existing class
without modify the class itself
●
In Java, we usually using static utility classes
let’s called it “util hell”
// java
public static void inflate(ViewGroup viewGroup, int layoutId) {
LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());
inflater.inflate(layoutId, viewGroup, false);
}
4. Extensions Functions
// kotlin
fun ViewGroup.inflate(layoutId: Int) = LayoutInflater.from(this.context)
.inflate(layoutId, this, false)
// we can call the function like this
override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
val root = parent.inflate(viewType)
return ViewHolder(root, itemClick)
}
5. Lambda Expression
“Anonymous function/code block”
Java:
●
Retrolambda
●
Android Studio’s lambda formatting “preview”
5. Lambda Expression
Implementation
●
Event listener, callback
●
Higher-order functions
With perks
●
Can be inlined for performant custom control structure
●
Closures
5. Lambda Expression
// java
Observable.just("Hello Rx")
.subscribe(
new Consumer<String>() {
@Override
public void accept(@NonNull String s) throws Exception {
System.out.println(s);
}
},
new Consumer<Throwable>() {
@Override
public void accept(@NonNull Throwable throwable) throws Exception
{
throwable.printStackTrace();
}
},
new Action() {
@Override
public void run() throws Exception {
System.out.println("Completed");
}
}
);
5. Lambda Expression
// Kotlin
Observable.just("Hello Kotlin Rx")
.subscribe(
{ value -> println(value) },
{ error -> error.printStackTrace() },
{ println("Completed") }
)
5. Lambda Expression
// Kotlin
Observable.just("Hello Kotlin Rx")
.subscribe(
{ println(it) },
{ it.printStackTrace() },
{ println("Completed") }
)
5. Lambda Expression
// Kotlin
Observable.just("Hello Kotlin Rx")
.subscribe(
::println,
Throwable::printStackTrace,
{ println("Completed") }
)
5.x Higher Order Function
●
Function that takes functions as parameter or returns a function
fun listCalculator(numbers: List<Int>, calculator: (List<Int>) -> Int) =
calculator(numbers)
fun main(args: Array<String>) {
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val sum = listCalculator(numbers, { numbers ->
var accumulate = 0
numbers.forEach { accumulate += it }
accumulate
})
val avg = listCalculator(numbers, { numbers ->
var accumulate = 0
numbers.forEach { accumulate += it }
accumulate / numbers.size
})
println("sum=$sum, avg=$avg")
}
5.x Higher Order Function
●
If function is the last paramater, we can do this
fun listCalculator(numbers: List<Int>, calculator: (List<Int>) -> Int) =
calculator(numbers)
fun main(args: Array<String>) {
val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
val sum = listCalculator(numbers) { numbers ->
var accumulate = 0
numbers.forEach { accumulate += it }
accumulate
}
val avg = listCalculator(numbers) { numbers ->
var accumulate = 0
numbers.forEach { accumulate += it }
accumulate / numbers.size
}
println("sum=$sum, avg=$avg")
}
5.x Extension Function Expressions
●
Extension Functions – Functions added to a type
without modifying the original.
●
Function Expressions – Undeclared function
bodies used an as expression (ie. data/value)
●
Higher Order Functions – Function which takes
function as parameter or returns a function
5.x Extension Function Expressions
db.beginTransaction()
try {
db.delete("movie", "title = ?", arrayOf("Logan"))
db.setTransactionSuccessful()
} finally {
db.endTransaction()
}
5.x Extension Function Expressions
fun SQLiteDatabase.useTransaction(func: () -> Unit) {
beginTransaction()
try {
func()
setTransactionSuccessful()
} finally {
endTransaction()
}
}
// code can be changed to
db.useTransaction {
db.delete("movie", "title = ?", arrayOf("Logan"))
}
5.x Extension Function Expressions
fun SQLiteDatabase.useTransaction(func: (SQLiteDatabase) -> Unit) {
beginTransaction()
try {
func(this)
setTransactionSuccessful()
} finally {
endTransaction()
}
}
// code can be changed to
db.useTransaction {
it.delete("movie", "title = ?", arrayOf("Logan"))
}
5.x Extension Function Expressions
fun SQLiteDatabase.useTransaction(func: SQLiteDatabase.() -> Unit) {
beginTransaction()
try {
this.func()
setTransactionSuccessful()
} finally {
endTransaction()
}
}
// code can be changed to
db.useTransaction {
delete("movie", "title = ?", arrayOf("Logan"))
}
5.x Extension Function Expressions
fun SQLiteDatabase.useTransaction(func: SQLiteDatabase.() -> Unit) {
beginTransaction()
try {
func()
setTransactionSuccessful()
} finally {
endTransaction()
}
}
db.useTransaction {
delete("movie", "title = ?", arrayOf("Logan"))
}
5.x Extension Function Expressions
inline fun SQLiteDatabase.useTransaction(func: SQLiteDatabase.() -> Unit) {
beginTransaction()
try {
func()
setTransactionSuccessful()
} finally {
endTransaction()
}
}
db.useTransaction {
delete("movie", "title = ?", arrayOf("Logan"))
}
// with inline keyword, code block will be inlined with caller code
// so, there is no overhead for creating lambda
5.x Extension Function Expressions
●
Higher order functions is very convenience to create our own DSL
●
For Android developer
– There is anko library which brings android layout to kotlin
code, not xml
– Its faster than xml, because actually android xml layout will be
compiled to java code first
// anko Android layout DSL example
verticalLayout {
val name = editText()
button("Say Hello") {
onClick { toast("Hello, ${name.text}!") }
}
}
6. Bonus
●
Collection API
●
apply
●
with
●
if expressions
●
when expressions
Thank you
and
Have a nice Kotlin!
Twitter: @ekosuhariyadi
FB: eko.suhariyadi
Email: eko.suhariyadi@gmail.com

Contenu connexe

Tendances

Tendances (20)

Kotlin a problem solver - gdd extended pune
Kotlin   a problem solver - gdd extended puneKotlin   a problem solver - gdd extended pune
Kotlin a problem solver - gdd extended pune
 
A short introduction to the Kotlin language for Java developers
A short introduction to the Kotlin language for Java developersA short introduction to the Kotlin language for Java developers
A short introduction to the Kotlin language for Java developers
 
Intro to kotlin
Intro to kotlinIntro to kotlin
Intro to kotlin
 
Android 101 - Kotlin ( Future of Android Development)
Android 101 - Kotlin ( Future of Android Development)Android 101 - Kotlin ( Future of Android Development)
Android 101 - Kotlin ( Future of Android Development)
 
Coding in kotlin
Coding in kotlinCoding in kotlin
Coding in kotlin
 
Introduction to Kotlin for Java developer
Introduction to Kotlin for Java developerIntroduction to Kotlin for Java developer
Introduction to Kotlin for Java developer
 
Kotlin presentation
Kotlin presentation Kotlin presentation
Kotlin presentation
 
Getting Started With Kotlin
Getting Started With KotlinGetting Started With Kotlin
Getting Started With Kotlin
 
Say Goodbye To Java: Getting Started With Kotlin For Android Development
Say Goodbye To Java: Getting Started With Kotlin For Android DevelopmentSay Goodbye To Java: Getting Started With Kotlin For Android Development
Say Goodbye To Java: Getting Started With Kotlin For Android Development
 
Exploring Anko Components, Kotlin, Android
Exploring Anko Components, Kotlin, AndroidExploring Anko Components, Kotlin, Android
Exploring Anko Components, Kotlin, Android
 
Kotlin L → ∞
Kotlin L → ∞Kotlin L → ∞
Kotlin L → ∞
 
Introduction to Kotlin JVM language
Introduction to Kotlin JVM languageIntroduction to Kotlin JVM language
Introduction to Kotlin JVM language
 
Future of Kotlin - How agile can language development be?
Future of Kotlin - How agile can language development be?Future of Kotlin - How agile can language development be?
Future of Kotlin - How agile can language development be?
 
JDD 2017: Kotlin for Java developers (Tomasz Kleszczyński)
JDD 2017: Kotlin for Java developers (Tomasz Kleszczyński)JDD 2017: Kotlin for Java developers (Tomasz Kleszczyński)
JDD 2017: Kotlin for Java developers (Tomasz Kleszczyński)
 
Introduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platformIntroduction to Kotlin Language and its application to Android platform
Introduction to Kotlin Language and its application to Android platform
 
Kotlin Overview
Kotlin OverviewKotlin Overview
Kotlin Overview
 
Kotlin for android
Kotlin for androidKotlin for android
Kotlin for android
 
Kotlin tlv
Kotlin tlvKotlin tlv
Kotlin tlv
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 
Modern Programming Languages - An overview
Modern Programming Languages - An overviewModern Programming Languages - An overview
Modern Programming Languages - An overview
 

Similaire à Having Fun with Kotlin Android - DILo Surabaya

Similaire à Having Fun with Kotlin Android - DILo Surabaya (20)

Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
 
Programming with Kotlin
Programming with KotlinProgramming with Kotlin
Programming with Kotlin
 
Koin Quickstart
Koin QuickstartKoin Quickstart
Koin Quickstart
 
Intro to Kotlin
Intro to KotlinIntro to Kotlin
Intro to Kotlin
 
Java For Automation
Java   For AutomationJava   For Automation
Java For Automation
 
Dear Kotliners - Java Developers are Humans too
Dear Kotliners - Java Developers are Humans tooDear Kotliners - Java Developers are Humans too
Dear Kotliners - Java Developers are Humans too
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
 
Android Application Development (1).pptx
Android Application Development (1).pptxAndroid Application Development (1).pptx
Android Application Development (1).pptx
 
Kotlin Native - C / Swift Interop - ACCU Autmn 2019
Kotlin Native - C / Swift Interop - ACCU Autmn 2019Kotlin Native - C / Swift Interop - ACCU Autmn 2019
Kotlin Native - C / Swift Interop - ACCU Autmn 2019
 
從零開始學 Android
從零開始學 Android從零開始學 Android
從零開始學 Android
 
Kotlin for all the Things
Kotlin for all the ThingsKotlin for all the Things
Kotlin for all the Things
 
Atlassian Groovy Plugins
Atlassian Groovy PluginsAtlassian Groovy Plugins
Atlassian Groovy Plugins
 
Kotlin intro
Kotlin introKotlin intro
Kotlin intro
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017Develop your next app with kotlin @ AndroidMakersFr 2017
Develop your next app with kotlin @ AndroidMakersFr 2017
 
What's New in Groovy 1.6?
What's New in Groovy 1.6?What's New in Groovy 1.6?
What's New in Groovy 1.6?
 
From Java to Kotlin - The first month in practice
From Java to Kotlin - The first month in practiceFrom Java to Kotlin - The first month in practice
From Java to Kotlin - The first month in practice
 
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018 Meetup di GDG Italia - Leonardo Pirro -  Codemotion Rome 2018
Meetup di GDG Italia - Leonardo Pirro - Codemotion Rome 2018
 
Exploring Kotlin
Exploring KotlinExploring Kotlin
Exploring Kotlin
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
 

Plus de DILo Surabaya (7)

Craate Your Own PHP Package - DILo Surabaya
Craate Your Own PHP Package - DILo SurabayaCraate Your Own PHP Package - DILo Surabaya
Craate Your Own PHP Package - DILo Surabaya
 
ERP an Introduction - DILo Surabaya
ERP an Introduction - DILo SurabayaERP an Introduction - DILo Surabaya
ERP an Introduction - DILo Surabaya
 
Introduction to Polymer Project - DILo Surabaya
Introduction to Polymer Project - DILo SurabayaIntroduction to Polymer Project - DILo Surabaya
Introduction to Polymer Project - DILo Surabaya
 
React Native - DILo Surabaya
React Native -  DILo SurabayaReact Native -  DILo Surabaya
React Native - DILo Surabaya
 
Open API Secification with Swagger - DILo Surabaya
Open API Secification with Swagger - DILo SurabayaOpen API Secification with Swagger - DILo Surabaya
Open API Secification with Swagger - DILo Surabaya
 
Gitflow - DILo Surabaya
Gitflow - DILo SurabayaGitflow - DILo Surabaya
Gitflow - DILo Surabaya
 
Concurrent Programming in Golang - DILo Surabaya
Concurrent Programming in Golang - DILo SurabayaConcurrent Programming in Golang - DILo Surabaya
Concurrent Programming in Golang - DILo Surabaya
 

Dernier

Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
kauryashika82
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
ZurliaSoop
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
negromaestrong
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
ciinovamais
 

Dernier (20)

On National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan FellowsOn National Teacher Day, meet the 2024-25 Kenan Fellows
On National Teacher Day, meet the 2024-25 Kenan Fellows
 
Holdier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdfHoldier Curriculum Vitae (April 2024).pdf
Holdier Curriculum Vitae (April 2024).pdf
 
Dyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptxDyslexia AI Workshop for Slideshare.pptx
Dyslexia AI Workshop for Slideshare.pptx
 
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in DelhiRussian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
Russian Escort Service in Delhi 11k Hotel Foreigner Russian Call Girls in Delhi
 
Unit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptxUnit-IV; Professional Sales Representative (PSR).pptx
Unit-IV; Professional Sales Representative (PSR).pptx
 
General Principles of Intellectual Property: Concepts of Intellectual Proper...
General Principles of Intellectual Property: Concepts of Intellectual  Proper...General Principles of Intellectual Property: Concepts of Intellectual  Proper...
General Principles of Intellectual Property: Concepts of Intellectual Proper...
 
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
Jual Obat Aborsi Hongkong ( Asli No.1 ) 085657271886 Obat Penggugur Kandungan...
 
Application orientated numerical on hev.ppt
Application orientated numerical on hev.pptApplication orientated numerical on hev.ppt
Application orientated numerical on hev.ppt
 
Unit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptxUnit-IV- Pharma. Marketing Channels.pptx
Unit-IV- Pharma. Marketing Channels.pptx
 
How to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POSHow to Manage Global Discount in Odoo 17 POS
How to Manage Global Discount in Odoo 17 POS
 
Seal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptxSeal of Good Local Governance (SGLG) 2024Final.pptx
Seal of Good Local Governance (SGLG) 2024Final.pptx
 
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdfUGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
UGC NET Paper 1 Mathematical Reasoning & Aptitude.pdf
 
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
TỔNG ÔN TẬP THI VÀO LỚP 10 MÔN TIẾNG ANH NĂM HỌC 2023 - 2024 CÓ ĐÁP ÁN (NGỮ Â...
 
Activity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdfActivity 01 - Artificial Culture (1).pdf
Activity 01 - Artificial Culture (1).pdf
 
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
2024-NATIONAL-LEARNING-CAMP-AND-OTHER.pptx
 
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
Explore beautiful and ugly buildings. Mathematics helps us create beautiful d...
 
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...Kodo Millet  PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
Kodo Millet PPT made by Ghanshyam bairwa college of Agriculture kumher bhara...
 
psychiatric nursing HISTORY COLLECTION .docx
psychiatric  nursing HISTORY  COLLECTION  .docxpsychiatric  nursing HISTORY  COLLECTION  .docx
psychiatric nursing HISTORY COLLECTION .docx
 
ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.ICT role in 21st century education and it's challenges.
ICT role in 21st century education and it's challenges.
 
How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17How to Give a Domain for a Field in Odoo 17
How to Give a Domain for a Field in Odoo 17
 

Having Fun with Kotlin Android - DILo Surabaya

  • 1. Having fun with Kotlin – Android Eko Suhariyadi
  • 2.
  • 3. What this presentation cover ● Kotlin introduction ● What we can achieve by using Kotlin for Android Development
  • 4. What is Kotlin ● Brand new programming language by JetBrains which targeting Java Platform, open sourced and free to use ● Kotlin is concise, safe, pragmatic, and focused on interoperability with Java code – Works great with all existing Java libraries and frameworks – Runs with same level performance as Java ● Can be used for server-side development, Android apps, Desktop apps, and much more. Anywhere Java runs ● It’s statically typed programming language ● Functional and Object Oriented – First-class functions – Immutability – No side-effects
  • 5. A bit History of Kotlin ● Internal project of JetBrains unveiled in July 2011 after a year of development – Seeking for language for future development – Scala is great, but compile time and interoperability is obvious deficiency ● Open sourced on February 2012 under Apache 2 license ● First v1.0 released on February 15, 2016 – It takes 6 years for the first stable release ● v1.1 just released on March 1, 2017 ● Named after Kotlin Island, near St. Petersburg, Russia. Where most JetBrains’ Kotlin development team work ● “Some part” of the language design is based on “Effective Java” book by Joshua Bloch
  • 6. Fun Facts? ● C takes 1 years to first stable release ● C++ takes 4 years ● Java takes 4 years ● Python takes 3 years ● JavaScript only takes 10 days :-) #DuaMingguJadi
  • 7. Installation ● Recommended way – Intellij IDEA or Android Studio plugin ● Standalone compiler – via SDKMAN (sdkman.io) – sdk install kotlin
  • 8. Why Kotlin ● (Android) Stuck on Java 6 – No streams – No lambda, method references ● Jack and Jill still on experimental (Java 8 support for Android) – No try-with-resources
  • 9. Why Kotlin ● (Android) Stuck on Java 6 – No streams Use RxJava – No lambda, method references ● Jack and Jill still on experimental (Java 8 support for Android) – No try-with-resources
  • 10. Why Kotlin ● (Android) Stuck on Java 6 – No streams Use RxJava – No lambda, method references Use Retrolambda ● Jack and Jill still on experimental (Java 8 support for Android) – No try-with-resources
  • 11. Why Kotlin ● (Android) Stuck on Java 6 – No streams Use RxJava – No lambda, method references Use Retrolambda ● Jack and Jill still on experimental (Java 8 support for Android) – No try-with-resources minSdkVersion = 19 or Use Retrolambda
  • 12. Why Kotlin ● (Android) Stuck on Java 6 ● Inability to add methods to platform types in Java – Achieved via Util class ● Nullability problems (*NullPointerException) in Java ● General verbosity / boilerplate code in Java – Too much code to achieve minimal jobs
  • 13. Taste of Kotlin data class Person(val name: String, val age: Int? = null) fun main(args: Array<String>) { val persons = listOf(Person("John Doe"), Person("Logan", age = 49)) val oldest = persons.maxBy { it.age ?: 0 } println("The oldest is $oldest") } // The oldest is Person(name=Logan, age=49) Bye bye semicolon ; Type after variable Nullability and default value Lambda expression String template/interpolation Data class Named parameter No “new”
  • 14. Taste of Kotlin ● Property declaration – val (*value) for immutable property, ie once initialized can’t be changed – var (*variable) for mutable property, can be reassign ● “fun” keyword to declare method/function – So literally we are having fun when code in Kotlin
  • 15. Taste of Kotlin fun someFunction(): Unit { // functions always have return value var say: String = "Kotlin is pragmatic language" say = "also safe and concise" val hello: String = "Domo Arigatou Mr. Roboto" hello = "updated hello" // compile time error return Unit } fun sum(x: Int, y: Int): Int { return x + y }
  • 16. Taste of Kotlin fun someFunction() { var say = "Kotlin is pragmatic language" say = "also safe and concise" val hello = "Domo Arigatou Mr. Roboto" // hello = "updated hello" } fun sum(x: Int, y: Int) = x + y // one liner // Type inference // compiler infer the type of properties without explicit declaration
  • 17. 1. Null Safety data class Contact(val name: String, var email: String? = null) { constructor(name: String) : this(name, null) } fun main(args: Array<String>) { val eko = Contact(email = "eko.suhariyadi@gmail.com", name = "Eko Suhariyadi") eko.name = null // compile error eko.email = null // ok }
  • 18. Working with null val eko = Contact("Eko Suhariyadi") // if email is null return other value, // with elvis operator ?: val email: String = eko.email ?: "Have no email" // cascading null safety val emailStrSize = eko.email?.length // safe scoping eko.email?.let { // send email // only executed if email is not null }
  • 19. 2. Conciseness Java: view.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { // do something } });
  • 20. 2. Conciseness Kotlin: view.setOnClickListener { // do something } view.setOnClickListener { view: View -> // do something with the view } view.setOnClickListener { view -> // do something with the view }
  • 21. 3. Data Class ● Write POJO class in Java is quite verbose – overloading constructor? – getter and setter – toString – hashCode and equals ● IDE could help for code generation ● Or by using libraries such as Google’s AutoValue
  • 22. 3. Data Classpublic class Todo { private String description; private Long createdAt; private boolean done; public Todo(String description, Long createdAt, boolean done) { this.description = description; this.createdAt = createdAt; this.done = done; } // ...
  • 23. 3. Data Classpublic class Todo { private String description; private Long createdAt; private boolean done; public Todo(String description, Long createdAt, boolean done) { this.description = description; this.createdAt = createdAt; this.done = done; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getCreatedAt() { return createdAt; } public void setCreatedAt(Long createdAt) { this.createdAt = createdAt; } public boolean isDone() { return done; } public void setDone(boolean done) { this.done = done; } // ...
  • 24. 3. Data Classpublic class Todo { private String description; private Long createdAt; private boolean done; public Todo(String description, Long createdAt, boolean done) { this.description = description; this.createdAt = createdAt; this.done = done; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public Long getCreatedAt() { return createdAt; } public void setCreatedAt(Long createdAt) { this.createdAt = createdAt; } public boolean isDone() { return done; } public void setDone(boolean done) { this.done = done; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; Todo todo = (Todo) o; if (done != todo.done) return false; return description != null ? description.equals(todo.description) : todo.description == null && (createdAt != null ? createdAt.equals(todo.createdAt) : todo.createdAt == null); } @Override public int hashCode() { int result = description != null ? description.hashCode() : 0; result = 31 * result + (createdAt != null ? createdAt.hashCode() : 0); result = 31 * result + (done ? 1 : 0); return result; } @Override public String toString() { return "Todo{" + "description='" + description + ''' + ", createdAt=" + createdAt + ", done=" + done + '}'; } }
  • 25. 3. Data Class data class TodoKotlin(var description: String, var createdAt: Long, var done: Boolean = false) → javap TodoKotlin.class public final class com.codangcoding.havingfunkotlin.TodoKotlin { public final java.lang.String getDescription(); public final void setDescription(java.lang.String); public final long getCreatedAt(); public final void setCreatedAt(long); public final boolean getDone(); public final void setDone(boolean); public com.codangcoding.havingfunkotlin.TodoKotlin(java.lang.String, long, boolean); public com.codangcoding.havingfunkotlin.TodoKotlin(java.lang.String, long, boolean, int, kotlin.jvm.internal.DefaultConstructorMarker); public final java.lang.String component1(); public final long component2(); public final boolean component3(); public final com.codangcoding.havingfunkotlin.TodoKotlin copy(java.lang.String, long, boolean); public static com.codangcoding.havingfunkotlin.TodoKotlin copy$default(com.codangcoding.havingfunkotlin.TodoKotlin, java.lang.String, long, boolean, int, java.lang.Object); public java.lang.String toString(); public int hashCode(); public boolean equals(java.lang.Object); }
  • 26. 3. Data Class ● Kotlin data class generate compiled code almost same with Java POJO ● But with extra method – component(N) for destructure – copy for “prototype pattern” val todo = TodoKotlin("Sample TODO", System.currentTimeMillis()) val (description, createdAt, done) = todo // destructure println("$description, $createdAt, $done") // need to destruct description and done only val (desc, _, finished) = todo println("$desc, $finished") // create new object by cloning from other val copiedTodo = todo.copy( description = "Copy from Sample TODO", done = true) println("""| |$todo |vs |$copiedTodo""".trimMargin())
  • 27. 4. Extensions Functions ● Ability to add functions or properties to existing class without modify the class itself ● In Java, we usually using static utility classes let’s called it “util hell” // java public static void inflate(ViewGroup viewGroup, int layoutId) { LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext()); inflater.inflate(layoutId, viewGroup, false); }
  • 28. 4. Extensions Functions // kotlin fun ViewGroup.inflate(layoutId: Int) = LayoutInflater.from(this.context) .inflate(layoutId, this, false) // we can call the function like this override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder { val root = parent.inflate(viewType) return ViewHolder(root, itemClick) }
  • 29. 5. Lambda Expression “Anonymous function/code block” Java: ● Retrolambda ● Android Studio’s lambda formatting “preview”
  • 30. 5. Lambda Expression Implementation ● Event listener, callback ● Higher-order functions With perks ● Can be inlined for performant custom control structure ● Closures
  • 31. 5. Lambda Expression // java Observable.just("Hello Rx") .subscribe( new Consumer<String>() { @Override public void accept(@NonNull String s) throws Exception { System.out.println(s); } }, new Consumer<Throwable>() { @Override public void accept(@NonNull Throwable throwable) throws Exception { throwable.printStackTrace(); } }, new Action() { @Override public void run() throws Exception { System.out.println("Completed"); } } );
  • 32. 5. Lambda Expression // Kotlin Observable.just("Hello Kotlin Rx") .subscribe( { value -> println(value) }, { error -> error.printStackTrace() }, { println("Completed") } )
  • 33. 5. Lambda Expression // Kotlin Observable.just("Hello Kotlin Rx") .subscribe( { println(it) }, { it.printStackTrace() }, { println("Completed") } )
  • 34. 5. Lambda Expression // Kotlin Observable.just("Hello Kotlin Rx") .subscribe( ::println, Throwable::printStackTrace, { println("Completed") } )
  • 35. 5.x Higher Order Function ● Function that takes functions as parameter or returns a function fun listCalculator(numbers: List<Int>, calculator: (List<Int>) -> Int) = calculator(numbers) fun main(args: Array<String>) { val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val sum = listCalculator(numbers, { numbers -> var accumulate = 0 numbers.forEach { accumulate += it } accumulate }) val avg = listCalculator(numbers, { numbers -> var accumulate = 0 numbers.forEach { accumulate += it } accumulate / numbers.size }) println("sum=$sum, avg=$avg") }
  • 36. 5.x Higher Order Function ● If function is the last paramater, we can do this fun listCalculator(numbers: List<Int>, calculator: (List<Int>) -> Int) = calculator(numbers) fun main(args: Array<String>) { val numbers = listOf(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) val sum = listCalculator(numbers) { numbers -> var accumulate = 0 numbers.forEach { accumulate += it } accumulate } val avg = listCalculator(numbers) { numbers -> var accumulate = 0 numbers.forEach { accumulate += it } accumulate / numbers.size } println("sum=$sum, avg=$avg") }
  • 37. 5.x Extension Function Expressions ● Extension Functions – Functions added to a type without modifying the original. ● Function Expressions – Undeclared function bodies used an as expression (ie. data/value) ● Higher Order Functions – Function which takes function as parameter or returns a function
  • 38. 5.x Extension Function Expressions db.beginTransaction() try { db.delete("movie", "title = ?", arrayOf("Logan")) db.setTransactionSuccessful() } finally { db.endTransaction() }
  • 39. 5.x Extension Function Expressions fun SQLiteDatabase.useTransaction(func: () -> Unit) { beginTransaction() try { func() setTransactionSuccessful() } finally { endTransaction() } } // code can be changed to db.useTransaction { db.delete("movie", "title = ?", arrayOf("Logan")) }
  • 40. 5.x Extension Function Expressions fun SQLiteDatabase.useTransaction(func: (SQLiteDatabase) -> Unit) { beginTransaction() try { func(this) setTransactionSuccessful() } finally { endTransaction() } } // code can be changed to db.useTransaction { it.delete("movie", "title = ?", arrayOf("Logan")) }
  • 41. 5.x Extension Function Expressions fun SQLiteDatabase.useTransaction(func: SQLiteDatabase.() -> Unit) { beginTransaction() try { this.func() setTransactionSuccessful() } finally { endTransaction() } } // code can be changed to db.useTransaction { delete("movie", "title = ?", arrayOf("Logan")) }
  • 42. 5.x Extension Function Expressions fun SQLiteDatabase.useTransaction(func: SQLiteDatabase.() -> Unit) { beginTransaction() try { func() setTransactionSuccessful() } finally { endTransaction() } } db.useTransaction { delete("movie", "title = ?", arrayOf("Logan")) }
  • 43. 5.x Extension Function Expressions inline fun SQLiteDatabase.useTransaction(func: SQLiteDatabase.() -> Unit) { beginTransaction() try { func() setTransactionSuccessful() } finally { endTransaction() } } db.useTransaction { delete("movie", "title = ?", arrayOf("Logan")) } // with inline keyword, code block will be inlined with caller code // so, there is no overhead for creating lambda
  • 44. 5.x Extension Function Expressions ● Higher order functions is very convenience to create our own DSL ● For Android developer – There is anko library which brings android layout to kotlin code, not xml – Its faster than xml, because actually android xml layout will be compiled to java code first // anko Android layout DSL example verticalLayout { val name = editText() button("Say Hello") { onClick { toast("Hello, ${name.text}!") } } }
  • 45. 6. Bonus ● Collection API ● apply ● with ● if expressions ● when expressions
  • 46. Thank you and Have a nice Kotlin! Twitter: @ekosuhariyadi FB: eko.suhariyadi Email: eko.suhariyadi@gmail.com