SlideShare a Scribd company logo
1 of 35
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

JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistAnton Arhipov
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Anton Arhipov
 
Google guava overview
Google guava overviewGoogle guava overview
Google guava overviewSteve Min
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 
Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016Danny Preussler
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahNick Plante
 
Letswift Swift 3.0
Letswift Swift 3.0Letswift Swift 3.0
Letswift Swift 3.0Sehyun Park
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersBartosz Kosarzycki
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesGanesh Samarthyam
 
Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and EffectsRaymond Roestenburg
 
Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)ThomasHorta
 

What's hot (20)

JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
 
Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012Mastering Java Bytecode With ASM - 33rd degree, 2012
Mastering Java Bytecode With ASM - 33rd degree, 2012
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
Google guava overview
Google guava overviewGoogle guava overview
Google guava overview
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016Unit testing without Robolectric, Droidcon Berlin 2016
Unit testing without Robolectric, Droidcon Berlin 2016
 
Building native Android applications with Mirah and Pindah
Building native Android applications with Mirah and PindahBuilding native Android applications with Mirah and Pindah
Building native Android applications with Mirah and Pindah
 
Letswift Swift 3.0
Letswift Swift 3.0Letswift Swift 3.0
Letswift Swift 3.0
 
Kotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developersKotlin advanced - language reference for android developers
Kotlin advanced - language reference for android developers
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
EMF Tips n Tricks
EMF Tips n TricksEMF Tips n Tricks
EMF Tips n Tricks
 
Akka tips
Akka tipsAkka tips
Akka tips
 
Java Concurrency by Example
Java Concurrency by ExampleJava Concurrency by Example
Java Concurrency by Example
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
Akka in-action
Akka in-actionAkka in-action
Akka in-action
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and Effects
 
Java serialization
Java serializationJava serialization
Java serialization
 
Don't do this
Don't do thisDon't do this
Don't do this
 
Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)
 

Viewers also liked

Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLsintelliyole
 
Exploring Anko Components, Kotlin, Android
Exploring Anko Components, Kotlin, AndroidExploring Anko Components, Kotlin, Android
Exploring Anko Components, Kotlin, AndroidRakshak R.Hegde
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
 
Getting started-kotlin-android
Getting started-kotlin-androidGetting started-kotlin-android
Getting started-kotlin-androidLucas Albuquerque
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinKai Koenig
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in actionCiro Rizzo
 
First few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesFirst few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesNebojša Vukšić
 

Viewers also liked (8)

Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
Exploring Anko Components, Kotlin, Android
Exploring Anko Components, Kotlin, AndroidExploring Anko Components, Kotlin, Android
Exploring Anko Components, Kotlin, Android
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
Getting started-kotlin-android
Getting started-kotlin-androidGetting started-kotlin-android
Getting started-kotlin-android
 
Little Helpers for Android Development with Kotlin
Little Helpers for Android Development with KotlinLittle Helpers for Android Development with Kotlin
Little Helpers for Android Development with Kotlin
 
Android Workshop
Android WorkshopAndroid Workshop
Android Workshop
 
Kotlin in action
Kotlin in actionKotlin in action
Kotlin in action
 
First few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examplesFirst few months with Kotlin - Introduction through android examples
First few months with Kotlin - Introduction through android examples
 

Similar to Android & Kotlin - The code awakens #03

Intro to scala
Intro to scalaIntro to scala
Intro to scalaJoe Zulli
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...Akaks
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Cody Engel
 
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 2017Arnaud Giuliani
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Mohamed Nabil, MSc.
 
Kotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparisonKotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparisonEd Austin
 
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 Codemotion
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvmIsaias Barroso
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalMichael Stal
 
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехБоремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехСбертех | SberTech
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Codemotion
 

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

Kotlin
KotlinKotlin
Kotlin
 
Scala introduction
Scala introductionScala introduction
Scala introduction
 
Intro to scala
Intro to scalaIntro to scala
Intro to scala
 
Kotlin intro
Kotlin introKotlin intro
Kotlin intro
 
Introduction to Scala
Introduction to ScalaIntroduction to Scala
Introduction to Scala
 
Wien15 java8
Wien15 java8Wien15 java8
Wien15 java8
 
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
documents.pub_new-features-in-java-8-it-jpoialjavanaitedwien15java8pdf-java-8...
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
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
 
Kotlin for Android Developers - 3
Kotlin for Android Developers - 3Kotlin for Android Developers - 3
Kotlin for Android Developers - 3
 
Kotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparisonKotlin Language Features - A Java comparison
Kotlin Language Features - A Java comparison
 
Java 5 Features
Java 5 FeaturesJava 5 Features
Java 5 Features
 
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
 
Scala uma poderosa linguagem para a jvm
Scala   uma poderosa linguagem para a jvmScala   uma poderosa linguagem para a jvm
Scala uma poderosa linguagem para a jvm
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехБоремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
 
Introduction kot iin
Introduction kot iinIntroduction kot iin
Introduction kot iin
 
Scala ntnu
Scala ntnuScala ntnu
Scala ntnu
 
Scala in a nutshell by venkat
Scala in a nutshell by venkatScala in a nutshell by venkat
Scala in a nutshell by venkat
 

Recently uploaded

WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension AidPhilip Schwarz
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationJuha-Pekka Tolvanen
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisamasabamasaba
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...chiefasafspells
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyviewmasabamasaba
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...Shane Coughlan
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park masabamasaba
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxAnnaArtyushina1
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplatePresentation.STUDIO
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2
 

Recently uploaded (20)

WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
WSO2CON 2024 - WSO2's Digital Transformation Journey with Choreo: A Platforml...
 
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
Direct Style Effect Systems -The Print[A] Example- A Comprehension AidDirect Style Effect Systems -The Print[A] Example- A Comprehension Aid
Direct Style Effect Systems - The Print[A] Example - A Comprehension Aid
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
WSO2Con2024 - From Code To Cloud: Fast Track Your Cloud Native Journey with C...
 
What Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the SituationWhat Goes Wrong with Language Definitions and How to Improve the Situation
What Goes Wrong with Language Definitions and How to Improve the Situation
 
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa%in tembisa+277-882-255-28 abortion pills for sale in tembisa
%in tembisa+277-882-255-28 abortion pills for sale in tembisa
 
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital TransformationWSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
WSO2Con2024 - WSO2's IAM Vision: Identity-Led Digital Transformation
 
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
Love witchcraft +27768521739 Binding love spell in Sandy Springs, GA |psychic...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
%in Hazyview+277-882-255-28 abortion pills for sale in Hazyview
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
OpenChain - The Ramifications of ISO/IEC 5230 and ISO/IEC 18974 for Legal Pro...
 
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
WSO2CON 2024 - Cloud Native Middleware: Domain-Driven Design, Cell-Based Arch...
 
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open SourceWSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
WSO2CON 2024 - Freedom First—Unleashing Developer Potential with Open Source
 
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park %in kempton park+277-882-255-28 abortion pills for sale in kempton park
%in kempton park+277-882-255-28 abortion pills for sale in kempton park
 
WSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - KeynoteWSO2Con204 - Hard Rock Presentation - Keynote
WSO2Con204 - Hard Rock Presentation - Keynote
 
Artyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptxArtyushina_Guest lecture_YorkU CS May 2024.pptx
Artyushina_Guest lecture_YorkU CS May 2024.pptx
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
AI & Machine Learning Presentation Template
AI & Machine Learning Presentation TemplateAI & Machine Learning Presentation Template
AI & Machine Learning Presentation Template
 
WSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go PlatformlessWSO2CON2024 - It's time to go Platformless
WSO2CON2024 - It's time to go Platformless
 

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