SlideShare a Scribd company logo
Android & Kotlin
The code awakens #03
Omar Miatello
Member of GDG Milano (Italy)
Android Developer @ Satispay
Personal profile
google.com/+OmarMiatello
Google+ Community: Kotlin for Android
goo.gl/mUKF1w
Google Presentation
#01 goo.gl/0jHLmE
#02 goo.gl/h3uG8M
#03 goo.gl/hnwvqu
Google Photo
#01 goo.gl/photos/cKP9L6zqZcxDRGzQ8
#02 goo.gl/photos/sXdpkbihCi5xAAnx7
#03 goo.gl/photos/P6kGhLE8yrWYnhAW6
Kotlin 1.0 is out - Read more: goo.gl/5DBQM2
dummy/HeroAdapter.java
public class HeroAdapter extends RecyclerView.Adapter<HeroAdapter.ViewHolder> {
private final List<HeroItem> mValues;
private final HeroOnClickListener mListener;
public HeroAdapter(List<HeroItem> items, HeroOnClickListener listener) {
mValues = items;
mListener = listener;
}
@Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_hero, parent, false);
return new ViewHolder(view);
}
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
HeroItem item = mValues.get(position);
“Convert Java File to Kotlin File”
CTRL + ALT + SHIFT + K
(or CMD + ALT + SHIFT + K)
Previously on Android & Kotlin #01: goo.gl/0jHLmE
Properties
val a: Int = 1 // val = READ ONLY (getter)
var b: Int = 1 // var = READ/WRITE (getter/setter)
String templates
"My name is $name $surname"
Lambdas
view.setOnClickListener { Log.d("TAG", "Item clicked!") }
Delegated properties (example: lazy)
val item by lazy { MyItem() }
// val = READ ONLY (getter)
// var = READ/WRITE (getter/setter)
val onlyRead = 1
var writable = 2
var nullable: Int? = 3
fun test() {
onlyRead = 3 // Error at compile time
writable = 3
writable = "test" // Error at compile time
writable = null // Error at compile time
nullable = null
}
// Customize getter/setter
val p1: Int = 1
get() {
// add some logic
return field
}
var p2: Int = 2
get() {
return field
}
set(value) {
// add some logic
field = value
}
Properties // More examples
var name = "Omar"
fun test() {
var str: String
str = "My name is $name"
str = "My name is $name (${name.length} chars)"
str = "$name == ${name}"
str = "$name.length != ${name.length}" // IS NOT THE SAME
str = "Time is: ${System.currentTimeMillis()}ms since 1970"
}
String templates // More examples
"qwerty | 123 | abc".filter { char ->
char.isDigit() // return is implicit in lambda expressions
}
"qwerty | 123 | abc".filter {
it.isDigit() // we can use "it" with 1 parameter
}
"qwerty | 123 | abc".filterIndexed { index: Int, c: Char ->
index > 3 && c.isLetterOrDigit()
}
Lambdas // More examples
val startTime by lazy { System.currentTimeMillis() }
var test by Delegates.observable(3) {
prop, old, new ->
if (new > old) Log.w("TEST", "$new > $old")
}
fun test() {
startTime
test = 5
test = 1
test = 2
val finish = System.currentTimeMillis() - startTime
}
Delegated properties // More examples
Previously on Android & Kotlin #02: goo.gl/h3uG8M
Null safety
var a: String = null // Error at compile time
var b: String? = null
Elvis Operator
val example: String = b ?: "Default" // b may be null
Smart-cast
if (myView is TextView) { myView.setText("Ciao") }
Collections
listOf("Android", "iOS", null).filterNotNull().map { it.toUpperCase() }
var test: String? = null
fun test() {
test = "new string"
test.length // Error at compile time
test?.length // if (test != null) test.length else null
test!!.length // test MUST exist or throw NullPointerException
val len = test?.length ?: 0 // default value = 0
test?.length ?: throw IllegalStateException("Missing the main string!")
}
Null safety & Elvis Operator // More examples
var test: Any? = "My new value"
fun test() {
val _test: Any? = test
if (_test != null) {
val checkEqual =
_test.equals("My new value")
if (_test is String) {
val checkLen = _test.length
_test.capitalize()
_test.substring(1)
}
}
when (_test) {
is Int -> {
val sum = _test + 1
}
is String -> {
val len = _test.length
}
}
}
Smart-cast // More examples
val stringList = listOf("my", "items", "list")
fun test() {
stringList.first()
stringList.filterNotNull()
stringList.filter { it.length > 3 }
stringList.first { it.length > 4 }
stringList.firstOrNull() { it.length > 10 }
stringList.findLast { it.startsWith("m") }
stringList.sorted()
stringList.indexOfLast { it.startsWith("i") }
stringList.map { it.length }
stringList.maxBy { it.length }
// ...
}
Collections // More examples
Kotlin vs Java - Part 3
Extensions
Infix Notation
Operator Overloading
fun String.isBig(): Boolean {
return length() > 10
}
#9 Kotlin - Extensions
http://kotlinlang.org/docs/reference/extensions.html
vs
fun String.isBig(): Boolean {
return length() > 10
}
fun example() {
"why?!".isBig() // false!
"harder, better, ...".isBig() // true!
}
#9 Kotlin - Extensions
http://kotlinlang.org/docs/reference/extensions.html
vs
fun String.isBig(): Boolean {
return length() > 10
}
fun example() {
"why?!".isBig() // false!
"harder, better, ...".isBig() // true!
}
// file MyUtils.java
class MyUtils {
static boolean isBig(String str) {
return str.length() > 10;
}
}
// file MyJavaClass.java
class MyJavaClass {
void example() {
MyUtils.isBig("why?!");
MyUtils.isBig("harder, better, ...");
}
}
#9 Kotlin - Extensions
http://kotlinlang.org/docs/reference/extensions.html
vs
fun String.isBig(): Boolean {
return length() > 10
}
fun example() {
"why?!".isBig()
"harder, better, ...".isBig()
}
// file MyUtils.java
class MyUtils {
static boolean isBig(String str) {
return str.length() > 10;
}
}
// file MyJavaClass.java
class MyJavaClass {
void example() {
MyUtils.isBig("why?!");
MyUtils.isBig("harder, better, ...");
}
}
#9 Kotlin - Extensions
http://kotlinlang.org/docs/reference/extensions.html
vs
class Hero(val power: Int) class Hero {
private final int power;
public Hero(int power) {
this.power = power;
}
}
#10 Kotlin - Infix Notation
http://kotlinlang.org/docs/reference/functions.html#infix-notation
vs
class Hero(val power: Int) {
infix fun vs(opponent: Hero): Hero {
return if (power > opponent.power) {
this
} else {
opponent
}
}
}
#10 Kotlin - Infix Notation
http://kotlinlang.org/docs/reference/functions.html#infix-notation
vs
class Hero(val power: Int) {
infix fun vs(opponent: Hero): Hero {
return if (power > opponent.power) {
this
} else {
opponent
}
}
}
fun example() {
val thor = Hero(7)
val ironman = Hero(8)
val spiderman = Hero(4)
}
// Skip Java version of Hero class,
// we use Kotlin class
class MyJavaClass {
void example() {
Hero thor = new Hero(7);
Hero ironman = new Hero(8);
Hero spiderman = new Hero(4);
}
}
#10 Kotlin - Infix Notation
http://kotlinlang.org/docs/reference/functions.html#infix-notation
vs
class Hero(val power: Int) {
infix fun vs(opponent: Hero): Hero {
return if (power > opponent.power) {
this
} else {
opponent
}
}
}
fun example() {
val thor = Hero(7)
val ironman = Hero(8)
val spiderman = Hero(4)
val theBest = thor vs ironman vs spiderman
}
// Skip Java version of Hero class,
// we use Kotlin class
class MyJavaClass {
void example() {
Hero thor = new Hero(7);
Hero ironman = new Hero(8);
Hero spiderman = new Hero(4);
Hero theBest =
thor.vs(ironman).vs(spiderman);
}
}
#10 Kotlin - Infix Notation
http://kotlinlang.org/docs/reference/functions.html#infix-notation
vs
class Hero(val power: Int) {
infix fun vs(opponent: Hero): Hero {
return if (power > opponent.power) {
this
} else {
opponent
}
}
}
fun example() {
val thor = Hero(7)
val ironman = Hero(8)
val spiderman = Hero(4)
val theBest = thor vs ironman vs spiderman
}
// Skip Java version of Hero class,
// we use Kotlin class
class MyJavaClass {
void example() {
Hero thor = new Hero(7);
Hero ironman = new Hero(8);
Hero spiderman = new Hero(4);
Hero theBest =
thor.vs(ironman).vs(spiderman);
}
}
#10 Kotlin - Infix Notation
http://kotlinlang.org/docs/reference/functions.html#infix-notation
vs
class Male(val eyes: String)
class Female(val hair: String)
class Male {
private String eyes;
public Male(String eyes) {
this.eyes = eyes;
}
}
class Female {
private String hair;
public Female(String hair) {
this.hair = hair;
}
}
#11 Kotlin - Operator Overloading
http://kotlinlang.org/docs/reference/operator-overloading.html
vs
class Male(val eyes: String)
class Female(val hair: String)
class Baby(val eyes: String, val hair: String)
// Skip Java version of Male, Female and Baby
// class, there is not enough space!
#11 Kotlin - Operator Overloading
http://kotlinlang.org/docs/reference/operator-overloading.html
vs
class Male(val eyes: String) {
operator fun plus(her: Female): Baby {
return Baby(this.eyes, her.hair)
}
}
class Female(val hair: String)
class Baby(val eyes: String, val hair: String)
// Skip Java version of Male, Female and Baby
// class, there is not enough space!
#11 Kotlin - Operator Overloading
http://kotlinlang.org/docs/reference/operator-overloading.html
vs
class Male(val eyes: String) {
operator fun plus(her: Female): Baby {
return Baby(this.eyes, her.hair)
}
}
class Female(val hair: String)
class Baby(val eyes: String, val hair: String)
fun example() {
val myBaby = Male("green") + Female("blond")
}
// Skip Java version of Male, Female and Baby
// class, there is not enough space!
class MyJavaClass {
void example() {
Baby myBaby = new Male("green").plus(
new Female("blond"));
}
}
#11 Kotlin - Operator Overloading
http://kotlinlang.org/docs/reference/operator-overloading.html
vs
class Male(val eyes: String) {
operator fun plus(her: Female): Baby {
return Baby(this.eyes, her.hair)
}
}
class Female(val hair: String)
class Baby(val eyes: String, val hair: String)
fun example() {
val myBaby = Male("green") + Female("blond")
}
// Skip Java version of Male, Female and Baby
// class, there is not enough space!
class MyJavaClass {
void example() {
Baby myBaby =
new Male("green").plus(new Female("blond"));
}
}
#11 Kotlin - Operator Overloading
http://kotlinlang.org/docs/reference/operator-overloading.html
vs
Android Example
from REAL code!
Extensions // More examples (1)
fun String.encodeUrl(charsetName: String = "UTF-8") = URLEncoder.encode(this, charsetName)
fun String.isValidEmail() = Patterns.EMAIL_ADDRESS.matcher(this).matches()
// INFO: https://en.wikipedia.org/wiki/Non-breaking_space
fun String.useNonBreakingSpace() = replace(' ', 'u00A0')
// http://developer.android.com/reference/android/content/Intent.html#ACTION_VIEW
fun Uri.viewIntent() = Intent(Intent.ACTION_VIEW).setData(this)
fun <T : View> T.onClick(onClick: (T) -> Unit) = setOnClickListener(onClick as (View) -> Unit)
fun View.postDelayed(delayMillis: Long, action: () -> Unit) = postDelayed(action, delayMillis)
val EditText.string: String
get() = text.toString()
Extensions // More examples (2)
fun View.hideSoftInput() {
val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
imm.hideSoftInputFromWindow(windowToken, 0)
}
/**
* Kotlin version of method Utils.isViewInBounds(container, view) by Alex Lockwood
* URL: https://github.com/alexjlockwood/activity-
transitions/blob/c4fa3a21c941691fb6bbe53e37cf3965842ee254/app/src/main/java/com/alexjlockwood/activity/transi
tions/Utils.java
*
* Returns true if {@param view} is contained within {@param container}'s bounds.
*/
fun View.isInBounds(container: View): Boolean {
val containerBounds = Rect()
container.getHitRect(containerBounds)
return getLocalVisibleRect(containerBounds)
}
Extensions + Infix Notation // More examples
infix fun String?.orNotNull(defaultValue: String): String =
if (!this.isNullOrBlank()) this!! else defaultValue
infix fun String?.or(defaultValue: String?): String? =
if (!this.isNullOrBlank()) this else defaultValue
// val a: String? = null
// val b: String? = null
// val c: String? = "test"
// val myText = a or b or c orNotNull "default"
Extensions + Operator Overloading // More examples
operator fun StringBuilder.plusAssign(s: String) { appendln(s) }
// val sb = StringBuilder()
// sb += "test"
// sb += "test2"
Questions?
Developers playground - #EX3
- In KotlinExample use: Extensions, Infix Notation, Operator Overloading
Start with: https://github.com/jacklt/KotlinExample/tree/ex2
Solution: https://github.com/jacklt/KotlinExample/tree/ex3 (at some point maybe …) :P
THANKS!
Omar Miatello, Member of GDG Milano (Italy)
Android Developer @ Satispay

More Related Content

What's hot (20)

PDF
JEEConf 2017 - Having fun with Javassist
Anton Arhipov
 
PPTX
Mastering Java Bytecode With ASM - 33rd degree, 2012
Anton Arhipov
 
PDF
Kotlin Generation
Minseo Chayabanjonglerd
 
PPT
Mastering Java ByteCode
Ecommerce Solution Provider SysIQ
 
PDF
Google guava overview
Steve Min
 
PDF
Google Guava for cleaner code
Mite Mitreski
 
PPTX
Unit testing without Robolectric, Droidcon Berlin 2016
Danny Preussler
 
PPTX
Building native Android applications with Mirah and Pindah
Nick Plante
 
PDF
Letswift Swift 3.0
Sehyun Park
 
PDF
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki
 
PDF
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
DOC
EMF Tips n Tricks
Kaniska Mandal
 
PDF
Akka tips
Raymond Roestenburg
 
PDF
Java Concurrency by Example
Ganesh Samarthyam
 
ODP
Ast transformations
HamletDRC
 
PPTX
Akka in-action
Raymond Roestenburg
 
PDF
Functions, Types, Programs and Effects
Raymond Roestenburg
 
PDF
Java serialization
Ecommerce Solution Provider SysIQ
 
PDF
Don't do this
Richard Jones
 
PDF
Kotlin Overview (PT-BR)
ThomasHorta
 
JEEConf 2017 - Having fun with Javassist
Anton Arhipov
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Anton Arhipov
 
Kotlin Generation
Minseo Chayabanjonglerd
 
Mastering Java ByteCode
Ecommerce Solution Provider SysIQ
 
Google guava overview
Steve Min
 
Google Guava for cleaner code
Mite Mitreski
 
Unit testing without Robolectric, Droidcon Berlin 2016
Danny Preussler
 
Building native Android applications with Mirah and Pindah
Nick Plante
 
Letswift Swift 3.0
Sehyun Park
 
Kotlin advanced - language reference for android developers
Bartosz Kosarzycki
 
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
EMF Tips n Tricks
Kaniska Mandal
 
Java Concurrency by Example
Ganesh Samarthyam
 
Ast transformations
HamletDRC
 
Akka in-action
Raymond Roestenburg
 
Functions, Types, Programs and Effects
Raymond Roestenburg
 
Don't do this
Richard Jones
 
Kotlin Overview (PT-BR)
ThomasHorta
 

Viewers also liked (8)

PPT
Smoothing Your Java with DSLs
intelliyole
 
PPTX
Exploring Anko Components, Kotlin, Android
Rakshak R.Hegde
 
PDF
No excuses, switch to kotlin
Thijs Suijten
 
PDF
Getting started-kotlin-android
Lucas Albuquerque
 
PDF
Little Helpers for Android Development with Kotlin
Kai Koenig
 
PPTX
Android Workshop
Rakshak R.Hegde
 
PDF
Kotlin in action
Ciro Rizzo
 
PDF
First few months with Kotlin - Introduction through android examples
Nebojša Vukšić
 
Smoothing Your Java with DSLs
intelliyole
 
Exploring Anko Components, Kotlin, Android
Rakshak R.Hegde
 
No excuses, switch to kotlin
Thijs Suijten
 
Getting started-kotlin-android
Lucas Albuquerque
 
Little Helpers for Android Development with Kotlin
Kai Koenig
 
Android Workshop
Rakshak R.Hegde
 
Kotlin in action
Ciro Rizzo
 
First few months with Kotlin - Introduction through android examples
Nebojša Vukšić
 
Ad

Similar to Android & Kotlin - The code awakens #03 (20)

PDF
Kotlin, smarter development for the jvm
Arnaud Giuliani
 
PDF
Develop your next app with kotlin @ AndroidMakersFr 2017
Arnaud Giuliani
 
PDF
Intro to Kotlin
Magda Miu
 
PPTX
Building Mobile Apps with Android
Kurt Renzo Acosta
 
PDF
Kotlin Introduction with Android applications
Thao Huynh Quang
 
PDF
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
STX Next
 
PDF
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
PDF
Kotlin what_you_need_to_know-converted event 4 with nigerians
junaidhasan17
 
PDF
Kotlin: A pragmatic language by JetBrains
Jigar Gosar
 
PDF
Having Fun with Kotlin Android - DILo Surabaya
DILo Surabaya
 
PPTX
Introduction to kotlin
Shaul Rosenzwieg
 
PPTX
Why kotlininandroid
Phani Kumar Gullapalli
 
PPTX
KotlinForJavaDevelopers-UJUG.pptx
Ian Robertson
 
PDF
Privet Kotlin (Windy City DevFest)
Cody Engel
 
PDF
Getting Started With Kotlin Development - Rivu
CodeOps Technologies LLP
 
PDF
Kotlin a problem solver - gdd extended pune
Hardik Trivedi
 
PDF
A quick and fast intro to Kotlin
XPeppers
 
PDF
Why Kotlin is your next language?
Aliaksei Zhynhiarouski
 
PDF
Let's fly to the Kotlin Island. Just an introduction to Kotlin
Aliaksei Zhynhiarouski
 
Kotlin, smarter development for the jvm
Arnaud Giuliani
 
Develop your next app with kotlin @ AndroidMakersFr 2017
Arnaud Giuliani
 
Intro to Kotlin
Magda Miu
 
Building Mobile Apps with Android
Kurt Renzo Acosta
 
Kotlin Introduction with Android applications
Thao Huynh Quang
 
Kotlin Developer Starter in Android - STX Next Lightning Talks - Feb 12, 2016
STX Next
 
Kotlin Developer Starter in Android projects
Bartosz Kosarzycki
 
Kotlin what_you_need_to_know-converted event 4 with nigerians
junaidhasan17
 
Kotlin: A pragmatic language by JetBrains
Jigar Gosar
 
Having Fun with Kotlin Android - DILo Surabaya
DILo Surabaya
 
Introduction to kotlin
Shaul Rosenzwieg
 
Why kotlininandroid
Phani Kumar Gullapalli
 
KotlinForJavaDevelopers-UJUG.pptx
Ian Robertson
 
Privet Kotlin (Windy City DevFest)
Cody Engel
 
Getting Started With Kotlin Development - Rivu
CodeOps Technologies LLP
 
Kotlin a problem solver - gdd extended pune
Hardik Trivedi
 
A quick and fast intro to Kotlin
XPeppers
 
Why Kotlin is your next language?
Aliaksei Zhynhiarouski
 
Let's fly to the Kotlin Island. Just an introduction to Kotlin
Aliaksei Zhynhiarouski
 
Ad

Recently uploaded (20)

PPTX
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
PDF
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
PDF
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
PPTX
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
PPTX
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PDF
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
PDF
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
PDF
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
PDF
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
PPTX
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
PPTX
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
PDF
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
PDF
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
PPTX
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
PDF
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
PDF
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
PPTX
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
PPTX
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
PDF
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
PDF
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 
Foundations of Marketo Engage - Powering Campaigns with Marketo Personalization
bbedford2
 
Automate Cybersecurity Tasks with Python
VICTOR MAESTRE RAMIREZ
 
SAP Firmaya İade ABAB Kodları - ABAB ile yazılmıl hazır kod örneği
Salih Küçük
 
Agentic Automation: Build & Deploy Your First UiPath Agent
klpathrudu
 
Homogeneity of Variance Test Options IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
IDM Crack with Internet Download Manager 6.42 Build 43 with Patch Latest 2025
bashirkhan333g
 
How to Hire AI Developers_ Step-by-Step Guide in 2025.pdf
DianApps Technologies
 
Top Agile Project Management Tools for Teams in 2025
Orangescrum
 
AI + DevOps = Smart Automation with devseccops.ai.pdf
Devseccops.ai
 
In From the Cold: Open Source as Part of Mainstream Software Asset Management
Shane Coughlan
 
OpenChain @ OSS NA - In From the Cold: Open Source as Part of Mainstream Soft...
Shane Coughlan
 
The 5 Reasons for IT Maintenance - Arna Softech
Arna Softech
 
MiniTool Power Data Recovery 8.8 With Crack New Latest 2025
bashirkhan333g
 
Home Care Tools: Benefits, features and more
Third Rock Techkno
 
SciPy 2025 - Packaging a Scientific Python Project
Henry Schreiner
 
Open Chain Q2 Steering Committee Meeting - 2025-06-25
Shane Coughlan
 
ChiSquare Procedure in IBM SPSS Statistics Version 31.pptx
Version 1 Analytics
 
Milwaukee Marketo User Group - Summer Road Trip: Mapping and Personalizing Yo...
bbedford2
 
iTop VPN With Crack Lifetime Activation Key-CODE
utfefguu
 
MiniTool Partition Wizard 12.8 Crack License Key LATEST
hashhshs786
 

Android & Kotlin - The code awakens #03

  • 1. Android & Kotlin The code awakens #03
  • 2. Omar Miatello Member of GDG Milano (Italy) Android Developer @ Satispay Personal profile google.com/+OmarMiatello Google+ Community: Kotlin for Android goo.gl/mUKF1w Google Presentation #01 goo.gl/0jHLmE #02 goo.gl/h3uG8M #03 goo.gl/hnwvqu Google Photo #01 goo.gl/photos/cKP9L6zqZcxDRGzQ8 #02 goo.gl/photos/sXdpkbihCi5xAAnx7 #03 goo.gl/photos/P6kGhLE8yrWYnhAW6
  • 3. Kotlin 1.0 is out - Read more: goo.gl/5DBQM2
  • 4. dummy/HeroAdapter.java public class HeroAdapter extends RecyclerView.Adapter<HeroAdapter.ViewHolder> { private final List<HeroItem> mValues; private final HeroOnClickListener mListener; public HeroAdapter(List<HeroItem> items, HeroOnClickListener listener) { mValues = items; mListener = listener; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_hero, parent, false); return new ViewHolder(view); } @Override public void onBindViewHolder(final ViewHolder holder, int position) { HeroItem item = mValues.get(position); “Convert Java File to Kotlin File” CTRL + ALT + SHIFT + K (or CMD + ALT + SHIFT + K)
  • 5. Previously on Android & Kotlin #01: goo.gl/0jHLmE Properties val a: Int = 1 // val = READ ONLY (getter) var b: Int = 1 // var = READ/WRITE (getter/setter) String templates "My name is $name $surname" Lambdas view.setOnClickListener { Log.d("TAG", "Item clicked!") } Delegated properties (example: lazy) val item by lazy { MyItem() }
  • 6. // val = READ ONLY (getter) // var = READ/WRITE (getter/setter) val onlyRead = 1 var writable = 2 var nullable: Int? = 3 fun test() { onlyRead = 3 // Error at compile time writable = 3 writable = "test" // Error at compile time writable = null // Error at compile time nullable = null } // Customize getter/setter val p1: Int = 1 get() { // add some logic return field } var p2: Int = 2 get() { return field } set(value) { // add some logic field = value } Properties // More examples
  • 7. var name = "Omar" fun test() { var str: String str = "My name is $name" str = "My name is $name (${name.length} chars)" str = "$name == ${name}" str = "$name.length != ${name.length}" // IS NOT THE SAME str = "Time is: ${System.currentTimeMillis()}ms since 1970" } String templates // More examples
  • 8. "qwerty | 123 | abc".filter { char -> char.isDigit() // return is implicit in lambda expressions } "qwerty | 123 | abc".filter { it.isDigit() // we can use "it" with 1 parameter } "qwerty | 123 | abc".filterIndexed { index: Int, c: Char -> index > 3 && c.isLetterOrDigit() } Lambdas // More examples
  • 9. val startTime by lazy { System.currentTimeMillis() } var test by Delegates.observable(3) { prop, old, new -> if (new > old) Log.w("TEST", "$new > $old") } fun test() { startTime test = 5 test = 1 test = 2 val finish = System.currentTimeMillis() - startTime } Delegated properties // More examples
  • 10. Previously on Android & Kotlin #02: goo.gl/h3uG8M Null safety var a: String = null // Error at compile time var b: String? = null Elvis Operator val example: String = b ?: "Default" // b may be null Smart-cast if (myView is TextView) { myView.setText("Ciao") } Collections listOf("Android", "iOS", null).filterNotNull().map { it.toUpperCase() }
  • 11. var test: String? = null fun test() { test = "new string" test.length // Error at compile time test?.length // if (test != null) test.length else null test!!.length // test MUST exist or throw NullPointerException val len = test?.length ?: 0 // default value = 0 test?.length ?: throw IllegalStateException("Missing the main string!") } Null safety & Elvis Operator // More examples
  • 12. var test: Any? = "My new value" fun test() { val _test: Any? = test if (_test != null) { val checkEqual = _test.equals("My new value") if (_test is String) { val checkLen = _test.length _test.capitalize() _test.substring(1) } } when (_test) { is Int -> { val sum = _test + 1 } is String -> { val len = _test.length } } } Smart-cast // More examples
  • 13. val stringList = listOf("my", "items", "list") fun test() { stringList.first() stringList.filterNotNull() stringList.filter { it.length > 3 } stringList.first { it.length > 4 } stringList.firstOrNull() { it.length > 10 } stringList.findLast { it.startsWith("m") } stringList.sorted() stringList.indexOfLast { it.startsWith("i") } stringList.map { it.length } stringList.maxBy { it.length } // ... } Collections // More examples
  • 14. Kotlin vs Java - Part 3 Extensions Infix Notation Operator Overloading
  • 15. fun String.isBig(): Boolean { return length() > 10 } #9 Kotlin - Extensions http://kotlinlang.org/docs/reference/extensions.html vs
  • 16. fun String.isBig(): Boolean { return length() > 10 } fun example() { "why?!".isBig() // false! "harder, better, ...".isBig() // true! } #9 Kotlin - Extensions http://kotlinlang.org/docs/reference/extensions.html vs
  • 17. fun String.isBig(): Boolean { return length() > 10 } fun example() { "why?!".isBig() // false! "harder, better, ...".isBig() // true! } // file MyUtils.java class MyUtils { static boolean isBig(String str) { return str.length() > 10; } } // file MyJavaClass.java class MyJavaClass { void example() { MyUtils.isBig("why?!"); MyUtils.isBig("harder, better, ..."); } } #9 Kotlin - Extensions http://kotlinlang.org/docs/reference/extensions.html vs
  • 18. fun String.isBig(): Boolean { return length() > 10 } fun example() { "why?!".isBig() "harder, better, ...".isBig() } // file MyUtils.java class MyUtils { static boolean isBig(String str) { return str.length() > 10; } } // file MyJavaClass.java class MyJavaClass { void example() { MyUtils.isBig("why?!"); MyUtils.isBig("harder, better, ..."); } } #9 Kotlin - Extensions http://kotlinlang.org/docs/reference/extensions.html vs
  • 19. class Hero(val power: Int) class Hero { private final int power; public Hero(int power) { this.power = power; } } #10 Kotlin - Infix Notation http://kotlinlang.org/docs/reference/functions.html#infix-notation vs
  • 20. class Hero(val power: Int) { infix fun vs(opponent: Hero): Hero { return if (power > opponent.power) { this } else { opponent } } } #10 Kotlin - Infix Notation http://kotlinlang.org/docs/reference/functions.html#infix-notation vs
  • 21. class Hero(val power: Int) { infix fun vs(opponent: Hero): Hero { return if (power > opponent.power) { this } else { opponent } } } fun example() { val thor = Hero(7) val ironman = Hero(8) val spiderman = Hero(4) } // Skip Java version of Hero class, // we use Kotlin class class MyJavaClass { void example() { Hero thor = new Hero(7); Hero ironman = new Hero(8); Hero spiderman = new Hero(4); } } #10 Kotlin - Infix Notation http://kotlinlang.org/docs/reference/functions.html#infix-notation vs
  • 22. class Hero(val power: Int) { infix fun vs(opponent: Hero): Hero { return if (power > opponent.power) { this } else { opponent } } } fun example() { val thor = Hero(7) val ironman = Hero(8) val spiderman = Hero(4) val theBest = thor vs ironman vs spiderman } // Skip Java version of Hero class, // we use Kotlin class class MyJavaClass { void example() { Hero thor = new Hero(7); Hero ironman = new Hero(8); Hero spiderman = new Hero(4); Hero theBest = thor.vs(ironman).vs(spiderman); } } #10 Kotlin - Infix Notation http://kotlinlang.org/docs/reference/functions.html#infix-notation vs
  • 23. class Hero(val power: Int) { infix fun vs(opponent: Hero): Hero { return if (power > opponent.power) { this } else { opponent } } } fun example() { val thor = Hero(7) val ironman = Hero(8) val spiderman = Hero(4) val theBest = thor vs ironman vs spiderman } // Skip Java version of Hero class, // we use Kotlin class class MyJavaClass { void example() { Hero thor = new Hero(7); Hero ironman = new Hero(8); Hero spiderman = new Hero(4); Hero theBest = thor.vs(ironman).vs(spiderman); } } #10 Kotlin - Infix Notation http://kotlinlang.org/docs/reference/functions.html#infix-notation vs
  • 24. class Male(val eyes: String) class Female(val hair: String) class Male { private String eyes; public Male(String eyes) { this.eyes = eyes; } } class Female { private String hair; public Female(String hair) { this.hair = hair; } } #11 Kotlin - Operator Overloading http://kotlinlang.org/docs/reference/operator-overloading.html vs
  • 25. class Male(val eyes: String) class Female(val hair: String) class Baby(val eyes: String, val hair: String) // Skip Java version of Male, Female and Baby // class, there is not enough space! #11 Kotlin - Operator Overloading http://kotlinlang.org/docs/reference/operator-overloading.html vs
  • 26. class Male(val eyes: String) { operator fun plus(her: Female): Baby { return Baby(this.eyes, her.hair) } } class Female(val hair: String) class Baby(val eyes: String, val hair: String) // Skip Java version of Male, Female and Baby // class, there is not enough space! #11 Kotlin - Operator Overloading http://kotlinlang.org/docs/reference/operator-overloading.html vs
  • 27. class Male(val eyes: String) { operator fun plus(her: Female): Baby { return Baby(this.eyes, her.hair) } } class Female(val hair: String) class Baby(val eyes: String, val hair: String) fun example() { val myBaby = Male("green") + Female("blond") } // Skip Java version of Male, Female and Baby // class, there is not enough space! class MyJavaClass { void example() { Baby myBaby = new Male("green").plus( new Female("blond")); } } #11 Kotlin - Operator Overloading http://kotlinlang.org/docs/reference/operator-overloading.html vs
  • 28. class Male(val eyes: String) { operator fun plus(her: Female): Baby { return Baby(this.eyes, her.hair) } } class Female(val hair: String) class Baby(val eyes: String, val hair: String) fun example() { val myBaby = Male("green") + Female("blond") } // Skip Java version of Male, Female and Baby // class, there is not enough space! class MyJavaClass { void example() { Baby myBaby = new Male("green").plus(new Female("blond")); } } #11 Kotlin - Operator Overloading http://kotlinlang.org/docs/reference/operator-overloading.html vs
  • 30. Extensions // More examples (1) fun String.encodeUrl(charsetName: String = "UTF-8") = URLEncoder.encode(this, charsetName) fun String.isValidEmail() = Patterns.EMAIL_ADDRESS.matcher(this).matches() // INFO: https://en.wikipedia.org/wiki/Non-breaking_space fun String.useNonBreakingSpace() = replace(' ', 'u00A0') // http://developer.android.com/reference/android/content/Intent.html#ACTION_VIEW fun Uri.viewIntent() = Intent(Intent.ACTION_VIEW).setData(this) fun <T : View> T.onClick(onClick: (T) -> Unit) = setOnClickListener(onClick as (View) -> Unit) fun View.postDelayed(delayMillis: Long, action: () -> Unit) = postDelayed(action, delayMillis) val EditText.string: String get() = text.toString()
  • 31. Extensions // More examples (2) fun View.hideSoftInput() { val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager imm.hideSoftInputFromWindow(windowToken, 0) } /** * Kotlin version of method Utils.isViewInBounds(container, view) by Alex Lockwood * URL: https://github.com/alexjlockwood/activity- transitions/blob/c4fa3a21c941691fb6bbe53e37cf3965842ee254/app/src/main/java/com/alexjlockwood/activity/transi tions/Utils.java * * Returns true if {@param view} is contained within {@param container}'s bounds. */ fun View.isInBounds(container: View): Boolean { val containerBounds = Rect() container.getHitRect(containerBounds) return getLocalVisibleRect(containerBounds) }
  • 32. Extensions + Infix Notation // More examples infix fun String?.orNotNull(defaultValue: String): String = if (!this.isNullOrBlank()) this!! else defaultValue infix fun String?.or(defaultValue: String?): String? = if (!this.isNullOrBlank()) this else defaultValue // val a: String? = null // val b: String? = null // val c: String? = "test" // val myText = a or b or c orNotNull "default"
  • 33. Extensions + Operator Overloading // More examples operator fun StringBuilder.plusAssign(s: String) { appendln(s) } // val sb = StringBuilder() // sb += "test" // sb += "test2"
  • 34. Questions? Developers playground - #EX3 - In KotlinExample use: Extensions, Infix Notation, Operator Overloading Start with: https://github.com/jacklt/KotlinExample/tree/ex2 Solution: https://github.com/jacklt/KotlinExample/tree/ex3 (at some point maybe …) :P
  • 35. THANKS! Omar Miatello, Member of GDG Milano (Italy) Android Developer @ Satispay