SlideShare a Scribd company logo
Android & Kotlin
The code awakens #02
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
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() }
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)
Kotlin vs Java - Part 2
Null-safety
Elvis Operator
Smart-cast
Collections
class MyKotlinClass {
val a: String = "ciao"
val b: String = null // Error at compile time
}
#5 Kotlin - Null Safety
http://kotlinlang.org/docs/reference/null-safety.html
vs
class MyKotlinClass {
val a: String = "ciao"
val b: String = null // Error at compile time
val c: String? = null
val d: String? = "ok"
}
#5 Kotlin - Null Safety
http://kotlinlang.org/docs/reference/null-safety.html
vs
class MyKotlinClass {
val a: String = "ciao"
val b: String = null // Error at compile time
val c: String? = null
val d: String? = "ok"
fun example(e: String, f: String?) {
e.length()
f.length() // Error at compile time
}
}
static class MyUtils {
void example(String e, String f) {
e.length(); // throw NullPointerException?
f.length(); // throw NullPointerException?
}
}
#5 Kotlin - Null Safety
http://kotlinlang.org/docs/reference/null-safety.html
vs
class MyKotlinClass {
val a: String = "ciao"
val b: String = null // Error at compile time
val c: String? = null
val d: String? = "ok"
fun example(e: String, f: String?) {
e.length()
f.length() // Error at compile time
f?.length()
}
}
static class MyUtils {
void example(String e, String f) {
e.length(); // throw NullPointerException?
f.length(); // throw NullPointerException?
}
}
#5 Kotlin - Null Safety
http://kotlinlang.org/docs/reference/null-safety.html
vs
class MyKotlinClass {
val a: String = "ciao"
val b: String = null // Error at compile time
val c: String? = null
val d: String? = "ok"
fun example(e: String, f: String?) {
e.length()
f.length() // Error at compile time
f?.length()
if (f != null) {
f.length()
}
}
}
static class MyUtils {
void example(String e, String f) {
e.length(); // throw NullPointerException?
f.length(); // throw NullPointerException?
if (e != null) {
e.length();
}
if (f != null) {
e.length();
}
}
}
#5 Kotlin - Null Safety
http://kotlinlang.org/docs/reference/null-safety.html
vs
val map = mapOf(
"dog" to "woof",
"cat" to "meow",
"bird" to "tweet",
"mouse" to "squeek")
fun sound(animal: String): String? {
return map.get(animal)
}
class MyUtils {
static Map<String, String> map = // ...
static String sound(String animal) {
return map.get(animal);
}
}
#6 Kotlin - Elvis Operator
http://kotlinlang.org/docs/reference/idioms.html#if-not-null-and-else-shorthand
vs
val map = mapOf(
"dog" to "woof",
"cat" to "meow",
"bird" to "tweet",
"mouse" to "squeek")
fun sound(animal: String): String? {
return map.get(animal)
}
fun example() {
val foxSay = sound("fox") ?: "No one knows"
}
class MyUtils {
static Map<String, String> map = // ...
static String sound(String animal) {
return map.get(animal);
}
static void example() {
String s = sound("fox");
String foxSay =
s != null ? s : "No one knows";
}
}
#6 Kotlin - Elvis Operator
http://kotlinlang.org/docs/reference/idioms.html#if-not-null-and-else-shorthand
vs
val map = mapOf(
"dog" to "woof",
"cat" to "meow",
"bird" to "tweet",
"mouse" to "squeek")
fun sound(animal: String): String? {
return map.get(animal)
}
fun example() {
val foxSay = sound("fox") ?: "No one knows"
}
class MyUtils {
static Map<String, String> map = // ...
static String sound(String animal) {
return map.get(animal);
}
static void example() {
String s = sound("fox");
String foxSay =
s != null ? s : "No one knows";
}
}
#6 Kotlin - Elvis Operator
http://kotlinlang.org/docs/reference/idioms.html#if-not-null-and-else-shorthand
vs
class MyUtils {
static void example(View myView) {
if (myView instanceof ImageView) {
}
}
}
#7 Kotlin - Smart Cast
http://kotlinlang.org/docs/reference/typecasts.html#smart-casts
vs
class MyUtils {
static void example(View myView) {
if (myView instanceof ImageView) {
ImageView imageView =
(ImageView) myView;
}
}
}
#7 Kotlin - Smart Cast
http://kotlinlang.org/docs/reference/typecasts.html#smart-casts
vs
class MyUtils {
static void example(View myView) {
if (myView instanceof ImageView) {
ImageView imageView =
(ImageView) myView;
imageView.setImageAlpha(10);
}
}
}
#7 Kotlin - Smart Cast
http://kotlinlang.org/docs/reference/typecasts.html#smart-casts
vs
class MyUtils {
static void example(View myView) {
if (myView instanceof ImageView) {
ImageView imageView =
(ImageView) myView;
imageView.setImageAlpha(10);
} else if (myView instanceof TextView) {
TextView textView = (TextView) myView;
textView.setText("Ciao");
}
}
}
#7 Kotlin - Smart Cast
http://kotlinlang.org/docs/reference/typecasts.html#smart-casts
vs
fun example1(myView: View) {
if (myView is ImageView) {
myView.setImageAlpha(10)
} else if (myView is TextView) {
myView.setText("Ciao")
}
}
class MyUtils {
static void example(View myView) {
if (myView instanceof ImageView) {
ImageView imageView =
(ImageView) myView;
imageView.setImageAlpha(10);
} else if (myView instanceof TextView) {
TextView textView = (TextView) myView;
textView.setText("Ciao");
}
}
}
#7 Kotlin - Smart Cast
http://kotlinlang.org/docs/reference/typecasts.html#smart-casts
vs
fun example1(myView: View) {
if (myView is ImageView) {
myView.setImageAlpha(10)
} else if (myView is TextView) {
myView.setText("Ciao")
}
}
fun example2(myView: View) {
when (myView) {
is ImageView -> myView.imageAlpha = 10
is TextView -> myView.text = "Ciao"
}
}
class MyUtils {
static void example(View myView) {
if (myView instanceof ImageView) {
ImageView imageView =
(ImageView) myView;
imageView.setImageAlpha(10);
} else if (myView instanceof TextView) {
TextView textView = (TextView) myView;
textView.setText("Ciao");
}
}
}
#7 Kotlin - Smart Cast
http://kotlinlang.org/docs/reference/typecasts.html#smart-casts
vs
fun example() {
val os = listOf("Android", "iOS", null,
"Windows Phone")
}
class MyUtils {
static void example() {
List<String> os = Arrays.asList("Android",
"iOS", null, "Windows Phone");
}
}
#8 Kotlin - Using collections
http://kotlinlang.org/docs/reference/basic-syntax.html#using-collections
vs
fun example() {
val os = listOf("Android", "iOS", null,
"Windows Phone")
os.filterNotNull()
}
class MyUtils {
static void example() {
List<String> os = Arrays.asList("Android",
"iOS", null, "Windows Phone");
List<String> osNotNull = new ArrayList<>();
for (String name : os) {
if (name != null) osNotNull.add(name);
}
}
}
#8 Kotlin - Using collections
http://kotlinlang.org/docs/reference/basic-syntax.html#using-collections
vs
fun example() {
val os = listOf("Android", "iOS", null,
"Windows Phone")
os.filterNotNull().sortedBy { it.length() }
}
class MyUtils {
static void example() {
List<String> os = Arrays.asList("Android",
"iOS", null, "Windows Phone");
List<String> osNotNull = new ArrayList<>();
for (String name : os) {
if (name != null) osNotNull.add(name);
}
Collections.sort(osNotNull, new
Comparator<String>() { @Override
public int compare(String l, String r) {
return r.length() - l.length();
}
});
}
}
#8 Kotlin - Using collections
http://kotlinlang.org/docs/reference/basic-syntax.html#using-collections
vs
fun example() {
val os = listOf("Android", "iOS", null,
"Windows Phone")
os.filterNotNull().sortedBy { it.length() }
.map { it.toUpperCase() }
}
class MyUtils {
static void example() {
List<String> os = Arrays.asList("Android",
"iOS", null, "Windows Phone");
List<String> osNotNull = new ArrayList<>();
for (String name : os) {
if (name != null) osNotNull.add(name);
}
Collections.sort(osNotNull, new
Comparator<String>() { @Override
public int compare(String l, String r) {
return l.length() - r.length();
}
});
for (String name : osNotNull) {
String value = name.toUpperCase();
}
}
}
#8 Kotlin - Using collections
http://kotlinlang.org/docs/reference/basic-syntax.html#using-collections
vs
fun example() {
val os = listOf("Android", "iOS", null,
"Windows Phone")
os.filterNotNull().sortedBy { it.length() }
.map { it.toUpperCase() }
.forEach { print(it) }
}
class MyUtils {
static void example() {
List<String> os = Arrays.asList("Android",
"iOS", null, "Windows Phone");
List<String> osNotNull = new ArrayList<>();
for (String name : os) {
if (name != null) osNotNull.add(name);
}
Collections.sort(osNotNull, new
Comparator<String>() { @Override
public int compare(String l, String r) {
return l.length() - r.length();
}
});
for (String name : osNotNull) {
String value = name.toUpperCase();
print(value);
}
} }
#8 Kotlin - Using collections
http://kotlinlang.org/docs/reference/basic-syntax.html#using-collections
vs
Android Example
From Java to Kotlin!
https://github.com/jacklt/KotlinExample/tree/ex1
dummy/Items.kt
data class HeroItem(val name: String, val gender: String, val power: Int)
dummy/HeroDummyContent.kt
object HeroDummyContent {
private val MALE = "Male"
private val FEMALE = "Female"
val ITEMS = listOf(
HeroItem("Hulk", MALE, 9),
HeroItem("Iron Man", MALE, 8),
HeroItem("Thor", MALE, 8),
HeroItem("Jessica Jones", FEMALE, 2),
HeroItem("Spiderman", MALE, 4)
)
}
dummy/HeroDummyContent.kt > object vs class
object HeroDummyContent {
private val MALE = "Male"
private val FEMALE = "Female"
val ITEMS = listOf(
HeroItem("Hulk", MALE, 9),
HeroItem("Iron Man", MALE, 8),
HeroItem("Thor", MALE, 8),
HeroItem("Jessica Jones", FEMALE, 2),
HeroItem("Spiderman", MALE, 4)
)
}
dummy/HeroDummyContent.kt > listOf(...)
object HeroDummyContent {
private val MALE = "Male"
private val FEMALE = "Female"
val ITEMS = listOf(
HeroItem("Hulk", MALE, 9),
HeroItem("Iron Man", MALE, 8),
HeroItem("Thor", MALE, 8),
HeroItem("Jessica Jones", FEMALE, 2),
HeroItem("Spiderman", MALE, 4)
)
}
dummy/HeroAdapter.kt
class HeroAdapter(val mValues: List<HeroItem>, val mListener: Function1<HeroItem, Unit>?) :
RecyclerView.Adapter<HeroAdapter.ViewHolder>() {
// ...
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val hero = mValues[position]
holder.item = hero
holder.nameView.text = "${hero.name} (Power: ${hero.power})"
holder.genderView.text = hero.gender
holder.itemView.setOnClickListener {
mListener?.invoke(hero)
}
}
// ...
}
dummy/HeroAdapter.kt > String template
class HeroAdapter(val mValues: List<HeroItem>, val mListener: Function1<HeroItem, Unit>?) :
RecyclerView.Adapter<HeroAdapter.ViewHolder>() {
// ...
override fun onBindViewHolder(holder: ViewHolder, position: Int) {
val hero = mValues[position]
holder.item = hero
holder.nameView.text = "${hero.name} (Power: ${hero.power})"
holder.genderView.text = hero.gender
holder.itemView.setOnClickListener {
mListener?.invoke(hero)
}
}
// ...
}
MainActivity.kt
class MainActivity : AppCompatActivity() {
private var currentHero: HeroItem? = null
private val adapter by lazy {
HeroAdapter(HeroDummyContent.ITEMS) {
// onItemClick ...
}
}
// ...
}
MainActivity.kt > adapter (lazy)
HeroAdapter(HeroDummyContent.ITEMS) { // onClick
val previousHero = currentHero
if (previousHero != null) { // fight
val conclusion = if (previousHero.power == it.power) {
"It's a draw"
} else if (previousHero.power > it.power) {
"${previousHero.name} wins!"
} else {
"${it.name} wins!"
}
Snackbar.make(fab, "${previousHero.name} vs ${it.name}!n$conclusion", Snackbar.LENGTH_LONG).show()
currentHero = null
} else { // assign current hero
Snackbar.make(fab, "Choose: ${it.name}", Snackbar.LENGTH_SHORT).show()
currentHero = it
}
}
MainActivity.kt > adapter (lazy) > Smart cast
HeroAdapter(HeroDummyContent.ITEMS) { // onClick
val previousHero = currentHero
if (previousHero != null) { // fight
val conclusion = if (previousHero.power == it.power) {
"It's a draw"
} else if (previousHero.power > it.power) {
"${previousHero.name} wins!"
} else {
"${it.name} wins!"
}
Snackbar.make(fab, "${previousHero.name} vs ${it.name}!n$conclusion", Snackbar.LENGTH_LONG).show()
currentHero = null
} else { // assign current hero
Snackbar.make(fab, "Choose: ${it.name}", Snackbar.LENGTH_SHORT).show()
currentHero = it
}
}
MainActivity.kt > adapter (lazy) > return if expression
HeroAdapter(HeroDummyContent.ITEMS) { // onClick
val previousHero = currentHero
if (previousHero != null) { // fight
val conclusion = if (previousHero.power == it.power) {
"It's a draw"
} else if (previousHero.power > it.power) {
"${previousHero.name} wins!"
} else {
"${it.name} wins!"
}
Snackbar.make(fab, "${previousHero.name} vs ${it.name}!n$conclusion", Snackbar.LENGTH_LONG).show()
currentHero = null
} else { // assign current hero
Snackbar.make(fab, "Choose: ${it.name}", Snackbar.LENGTH_SHORT).show()
currentHero = it
}
}
Questions?
Developers playground - #EX2
- Aggiungere le proprietà a HeroItem: hair (String?), eyes (String?)
- Mostrarle (se presenti) nella lista
- Se vengono scelti 2 eroi di sesso opposto, viene creato un nuovo eroe
- Si possono usare le proprietà dei genitori, oppure dei valori di default se
mancano
Start with: https://github.com/jacklt/KotlinExample/tree/ex1
Solution: https://github.com/jacklt/KotlinExample/tree/ex2
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 Javassist
Anton Arhipov
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
Minseo Chayabanjonglerd
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code Generation
Ivan Dolgushin
 
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
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee conf
Igor Anishchenko
 
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
Danny Preussler
 
Google guava
Google guavaGoogle guava
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
Bartosz Kosarzycki
 
Google guava overview
Google guava overviewGoogle guava overview
Google guava overview
Steve Min
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
HamletDRC
 
EMF Tips n Tricks
EMF Tips n TricksEMF Tips n Tricks
EMF Tips n Tricks
Kaniska Mandal
 
Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)
ThomasHorta
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
Mite Mitreski
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
Ecommerce Solution Provider SysIQ
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
Jordi Gerona
 
Monads asking the right question
Monads  asking the right questionMonads  asking the right question
Monads asking the right question
Pawel Szulc
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
Ganesh Samarthyam
 
Akka in-action
Akka in-actionAkka in-action
Akka in-action
Raymond Roestenburg
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and Effects
Raymond Roestenburg
 

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
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code Generation
 
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
 
Clean code with google guava jee conf
Clean code with google guava jee confClean code with google guava jee conf
Clean code with google guava jee conf
 
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
 
Google guava
Google guavaGoogle guava
Google guava
 
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
 
Google guava overview
Google guava overviewGoogle guava overview
Google guava overview
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
EMF Tips n Tricks
EMF Tips n TricksEMF Tips n Tricks
EMF Tips n Tricks
 
Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)Kotlin Overview (PT-BR)
Kotlin Overview (PT-BR)
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
Google Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & AndroidGoogle Guava - Core libraries for Java & Android
Google Guava - Core libraries for Java & Android
 
Monads asking the right question
Monads  asking the right questionMonads  asking the right question
Monads asking the right question
 
Advanced Debugging Using Java Bytecodes
Advanced Debugging Using Java BytecodesAdvanced Debugging Using Java Bytecodes
Advanced Debugging Using Java Bytecodes
 
Akka in-action
Akka in-actionAkka in-action
Akka in-action
 
Java serialization
Java serializationJava serialization
Java serialization
 
Functions, Types, Programs and Effects
Functions, Types, Programs and EffectsFunctions, Types, Programs and Effects
Functions, Types, Programs and Effects
 

Viewers also liked

Easy Powder Presentation
Easy Powder PresentationEasy Powder Presentation
Easy Powder PresentationEren Isitan
 
Que es un blog
Que es un blogQue es un blog
Que es un blog
anthony salgado
 
Průběh výstavby přízemního domu s obytným podkrovím
Průběh výstavby přízemního domu s obytným podkrovímPrůběh výstavby přízemního domu s obytným podkrovím
Průběh výstavby přízemního domu s obytným podkrovím
dshana
 
Give your employer brand a kickstart!
Give your employer brand a kickstart!Give your employer brand a kickstart!
Give your employer brand a kickstart!
Employment Office
 
Presentazione workcamp di monaco
Presentazione workcamp di monacoPresentazione workcamp di monaco
Presentazione workcamp di monaco
Piero Pavanini
 
Presentación ¿Qué es el PP?
Presentación ¿Qué es el PP?Presentación ¿Qué es el PP?
Presentación ¿Qué es el PP?
Wendy Ramos
 
¡Que viva la musica!
¡Que viva la musica!¡Que viva la musica!
¡Que viva la musica!
SAMUEL ALEJANDRO
 
Macchina Peck Final Project (1)
Macchina Peck Final Project (1)Macchina Peck Final Project (1)
Macchina Peck Final Project (1)Ryan Crowell
 
Final Portfolio
Final PortfolioFinal Portfolio
Final Portfolio
todd_patch
 
Eml pp bio 2016
Eml pp bio 2016Eml pp bio 2016
Eml pp bio 2016
BelizeEnergyManagement
 
Operations excellence
Operations excellenceOperations excellence
Operations excellence
The Apparel Logistics Group
 
DIAPOSITIVA DE LAS COMPETENCIAS DIGITALES
DIAPOSITIVA DE LAS COMPETENCIAS DIGITALES DIAPOSITIVA DE LAS COMPETENCIAS DIGITALES
DIAPOSITIVA DE LAS COMPETENCIAS DIGITALES
melizatorres03
 

Viewers also liked (13)

Easy Powder Presentation
Easy Powder PresentationEasy Powder Presentation
Easy Powder Presentation
 
Que es un blog
Que es un blogQue es un blog
Que es un blog
 
Průběh výstavby přízemního domu s obytným podkrovím
Průběh výstavby přízemního domu s obytným podkrovímPrůběh výstavby přízemního domu s obytným podkrovím
Průběh výstavby přízemního domu s obytným podkrovím
 
Give your employer brand a kickstart!
Give your employer brand a kickstart!Give your employer brand a kickstart!
Give your employer brand a kickstart!
 
Presentazione workcamp di monaco
Presentazione workcamp di monacoPresentazione workcamp di monaco
Presentazione workcamp di monaco
 
Presentación ¿Qué es el PP?
Presentación ¿Qué es el PP?Presentación ¿Qué es el PP?
Presentación ¿Qué es el PP?
 
¡Que viva la musica!
¡Que viva la musica!¡Que viva la musica!
¡Que viva la musica!
 
BDTB
BDTBBDTB
BDTB
 
Macchina Peck Final Project (1)
Macchina Peck Final Project (1)Macchina Peck Final Project (1)
Macchina Peck Final Project (1)
 
Final Portfolio
Final PortfolioFinal Portfolio
Final Portfolio
 
Eml pp bio 2016
Eml pp bio 2016Eml pp bio 2016
Eml pp bio 2016
 
Operations excellence
Operations excellenceOperations excellence
Operations excellence
 
DIAPOSITIVA DE LAS COMPETENCIAS DIGITALES
DIAPOSITIVA DE LAS COMPETENCIAS DIGITALES DIAPOSITIVA DE LAS COMPETENCIAS DIGITALES
DIAPOSITIVA DE LAS COMPETENCIAS DIGITALES
 

Similar to Android & Kotlin - The code awakens #02

Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
Kurt Renzo Acosta
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
Cody Engel
 
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
 
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
Codemotion
 
Having Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaHaving Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo Surabaya
DILo Surabaya
 
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
Arnaud Giuliani
 
Kotlin intro
Kotlin introKotlin intro
Kotlin intro
Elifarley Cruz
 
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехБоремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Сбертех | SberTech
 
Why Kotlin is your next language?
Why Kotlin is your next language? Why Kotlin is your next language?
Why Kotlin is your next language?
Aliaksei Zhynhiarouski
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
Arnaud Giuliani
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
TechMagic
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
Squareboat
 
Save time with kotlin in android development
Save time with kotlin in android developmentSave time with kotlin in android development
Save time with kotlin in android development
Adit Lal
 
Practical tips for building apps with kotlin
Practical tips for building apps with kotlinPractical tips for building apps with kotlin
Practical tips for building apps with kotlin
Adit Lal
 
Kotlin on android
Kotlin on androidKotlin on android
Kotlin on android
Kurt Renzo Acosta
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
Arawn Park
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
Adit Lal
 
Reducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Reducing boilerplate with Kotlin, KTX and Kotlin Android ExtensionsReducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Reducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Patrick Steiger
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
Michael Stal
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
VMware Tanzu
 

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

Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
 
Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)Privet Kotlin (Windy City DevFest)
Privet Kotlin (Windy City DevFest)
 
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
 
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
 
Having Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo SurabayaHaving Fun with Kotlin Android - DILo Surabaya
Having Fun with Kotlin Android - DILo Surabaya
 
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 intro
Kotlin introKotlin intro
Kotlin intro
 
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТехБоремся с NPE вместе с Kotlin, Павел Шацких СберТех
Боремся с NPE вместе с Kotlin, Павел Шацких СберТех
 
Why Kotlin is your next language?
Why Kotlin is your next language? Why Kotlin is your next language?
Why Kotlin is your next language?
 
Kotlin, smarter development for the jvm
Kotlin, smarter development for the jvmKotlin, smarter development for the jvm
Kotlin, smarter development for the jvm
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
What’s new in Kotlin?
What’s new in Kotlin?What’s new in Kotlin?
What’s new in Kotlin?
 
Save time with kotlin in android development
Save time with kotlin in android developmentSave time with kotlin in android development
Save time with kotlin in android development
 
Practical tips for building apps with kotlin
Practical tips for building apps with kotlinPractical tips for building apps with kotlin
Practical tips for building apps with kotlin
 
Kotlin on android
Kotlin on androidKotlin on android
Kotlin on android
 
#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기#살아있다 #자프링외길12년차 #코프링2개월생존기
#살아있다 #자프링외길12년차 #코프링2개월생존기
 
Kotlin for Android devs
Kotlin for Android devsKotlin for Android devs
Kotlin for Android devs
 
Reducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Reducing boilerplate with Kotlin, KTX and Kotlin Android ExtensionsReducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
Reducing boilerplate with Kotlin, KTX and Kotlin Android Extensions
 
Oop2010 Scala Presentation Stal
Oop2010 Scala Presentation StalOop2010 Scala Presentation Stal
Oop2010 Scala Presentation Stal
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
 

Recently uploaded

Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
e20449
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Globus
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
wottaspaceseo
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Shahin Sheidaei
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Globus
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
WSO2
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
Cyanic lab
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
Tier1 app
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
Globus
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
Globus
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Globus
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
Paco van Beckhoven
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
Georgi Kodinov
 

Recently uploaded (20)

Graphic Design Crash Course for beginners
Graphic Design Crash Course for beginnersGraphic Design Crash Course for beginners
Graphic Design Crash Course for beginners
 
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
Innovating Inference - Remote Triggering of Large Language Models on HPC Clus...
 
How Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptxHow Recreation Management Software Can Streamline Your Operations.pptx
How Recreation Management Software Can Streamline Your Operations.pptx
 
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
Gamify Your Mind; The Secret Sauce to Delivering Success, Continuously Improv...
 
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
Climate Science Flows: Enabling Petabyte-Scale Climate Analysis with the Eart...
 
Accelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with PlatformlessAccelerate Enterprise Software Engineering with Platformless
Accelerate Enterprise Software Engineering with Platformless
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 
Cyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdfCyaniclab : Software Development Agency Portfolio.pdf
Cyaniclab : Software Development Agency Portfolio.pdf
 
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERRORTROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
TROUBLESHOOTING 9 TYPES OF OUTOFMEMORYERROR
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Vitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume MontevideoVitthal Shirke Microservices Resume Montevideo
Vitthal Shirke Microservices Resume Montevideo
 
First Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User EndpointsFirst Steps with Globus Compute Multi-User Endpoints
First Steps with Globus Compute Multi-User Endpoints
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Understanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSageUnderstanding Globus Data Transfers with NetSage
Understanding Globus Data Transfers with NetSage
 
Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...Developing Distributed High-performance Computing Capabilities of an Open Sci...
Developing Distributed High-performance Computing Capabilities of an Open Sci...
 
Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024Cracking the code review at SpringIO 2024
Cracking the code review at SpringIO 2024
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx2024 RoOUG Security model for the cloud.pptx
2024 RoOUG Security model for the cloud.pptx
 

Android & Kotlin - The code awakens #02

  • 1. Android & Kotlin The code awakens #02
  • 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. 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() }
  • 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. Kotlin vs Java - Part 2 Null-safety Elvis Operator Smart-cast Collections
  • 6. class MyKotlinClass { val a: String = "ciao" val b: String = null // Error at compile time } #5 Kotlin - Null Safety http://kotlinlang.org/docs/reference/null-safety.html vs
  • 7. class MyKotlinClass { val a: String = "ciao" val b: String = null // Error at compile time val c: String? = null val d: String? = "ok" } #5 Kotlin - Null Safety http://kotlinlang.org/docs/reference/null-safety.html vs
  • 8. class MyKotlinClass { val a: String = "ciao" val b: String = null // Error at compile time val c: String? = null val d: String? = "ok" fun example(e: String, f: String?) { e.length() f.length() // Error at compile time } } static class MyUtils { void example(String e, String f) { e.length(); // throw NullPointerException? f.length(); // throw NullPointerException? } } #5 Kotlin - Null Safety http://kotlinlang.org/docs/reference/null-safety.html vs
  • 9. class MyKotlinClass { val a: String = "ciao" val b: String = null // Error at compile time val c: String? = null val d: String? = "ok" fun example(e: String, f: String?) { e.length() f.length() // Error at compile time f?.length() } } static class MyUtils { void example(String e, String f) { e.length(); // throw NullPointerException? f.length(); // throw NullPointerException? } } #5 Kotlin - Null Safety http://kotlinlang.org/docs/reference/null-safety.html vs
  • 10. class MyKotlinClass { val a: String = "ciao" val b: String = null // Error at compile time val c: String? = null val d: String? = "ok" fun example(e: String, f: String?) { e.length() f.length() // Error at compile time f?.length() if (f != null) { f.length() } } } static class MyUtils { void example(String e, String f) { e.length(); // throw NullPointerException? f.length(); // throw NullPointerException? if (e != null) { e.length(); } if (f != null) { e.length(); } } } #5 Kotlin - Null Safety http://kotlinlang.org/docs/reference/null-safety.html vs
  • 11. val map = mapOf( "dog" to "woof", "cat" to "meow", "bird" to "tweet", "mouse" to "squeek") fun sound(animal: String): String? { return map.get(animal) } class MyUtils { static Map<String, String> map = // ... static String sound(String animal) { return map.get(animal); } } #6 Kotlin - Elvis Operator http://kotlinlang.org/docs/reference/idioms.html#if-not-null-and-else-shorthand vs
  • 12. val map = mapOf( "dog" to "woof", "cat" to "meow", "bird" to "tweet", "mouse" to "squeek") fun sound(animal: String): String? { return map.get(animal) } fun example() { val foxSay = sound("fox") ?: "No one knows" } class MyUtils { static Map<String, String> map = // ... static String sound(String animal) { return map.get(animal); } static void example() { String s = sound("fox"); String foxSay = s != null ? s : "No one knows"; } } #6 Kotlin - Elvis Operator http://kotlinlang.org/docs/reference/idioms.html#if-not-null-and-else-shorthand vs
  • 13. val map = mapOf( "dog" to "woof", "cat" to "meow", "bird" to "tweet", "mouse" to "squeek") fun sound(animal: String): String? { return map.get(animal) } fun example() { val foxSay = sound("fox") ?: "No one knows" } class MyUtils { static Map<String, String> map = // ... static String sound(String animal) { return map.get(animal); } static void example() { String s = sound("fox"); String foxSay = s != null ? s : "No one knows"; } } #6 Kotlin - Elvis Operator http://kotlinlang.org/docs/reference/idioms.html#if-not-null-and-else-shorthand vs
  • 14. class MyUtils { static void example(View myView) { if (myView instanceof ImageView) { } } } #7 Kotlin - Smart Cast http://kotlinlang.org/docs/reference/typecasts.html#smart-casts vs
  • 15. class MyUtils { static void example(View myView) { if (myView instanceof ImageView) { ImageView imageView = (ImageView) myView; } } } #7 Kotlin - Smart Cast http://kotlinlang.org/docs/reference/typecasts.html#smart-casts vs
  • 16. class MyUtils { static void example(View myView) { if (myView instanceof ImageView) { ImageView imageView = (ImageView) myView; imageView.setImageAlpha(10); } } } #7 Kotlin - Smart Cast http://kotlinlang.org/docs/reference/typecasts.html#smart-casts vs
  • 17. class MyUtils { static void example(View myView) { if (myView instanceof ImageView) { ImageView imageView = (ImageView) myView; imageView.setImageAlpha(10); } else if (myView instanceof TextView) { TextView textView = (TextView) myView; textView.setText("Ciao"); } } } #7 Kotlin - Smart Cast http://kotlinlang.org/docs/reference/typecasts.html#smart-casts vs
  • 18. fun example1(myView: View) { if (myView is ImageView) { myView.setImageAlpha(10) } else if (myView is TextView) { myView.setText("Ciao") } } class MyUtils { static void example(View myView) { if (myView instanceof ImageView) { ImageView imageView = (ImageView) myView; imageView.setImageAlpha(10); } else if (myView instanceof TextView) { TextView textView = (TextView) myView; textView.setText("Ciao"); } } } #7 Kotlin - Smart Cast http://kotlinlang.org/docs/reference/typecasts.html#smart-casts vs
  • 19. fun example1(myView: View) { if (myView is ImageView) { myView.setImageAlpha(10) } else if (myView is TextView) { myView.setText("Ciao") } } fun example2(myView: View) { when (myView) { is ImageView -> myView.imageAlpha = 10 is TextView -> myView.text = "Ciao" } } class MyUtils { static void example(View myView) { if (myView instanceof ImageView) { ImageView imageView = (ImageView) myView; imageView.setImageAlpha(10); } else if (myView instanceof TextView) { TextView textView = (TextView) myView; textView.setText("Ciao"); } } } #7 Kotlin - Smart Cast http://kotlinlang.org/docs/reference/typecasts.html#smart-casts vs
  • 20. fun example() { val os = listOf("Android", "iOS", null, "Windows Phone") } class MyUtils { static void example() { List<String> os = Arrays.asList("Android", "iOS", null, "Windows Phone"); } } #8 Kotlin - Using collections http://kotlinlang.org/docs/reference/basic-syntax.html#using-collections vs
  • 21. fun example() { val os = listOf("Android", "iOS", null, "Windows Phone") os.filterNotNull() } class MyUtils { static void example() { List<String> os = Arrays.asList("Android", "iOS", null, "Windows Phone"); List<String> osNotNull = new ArrayList<>(); for (String name : os) { if (name != null) osNotNull.add(name); } } } #8 Kotlin - Using collections http://kotlinlang.org/docs/reference/basic-syntax.html#using-collections vs
  • 22. fun example() { val os = listOf("Android", "iOS", null, "Windows Phone") os.filterNotNull().sortedBy { it.length() } } class MyUtils { static void example() { List<String> os = Arrays.asList("Android", "iOS", null, "Windows Phone"); List<String> osNotNull = new ArrayList<>(); for (String name : os) { if (name != null) osNotNull.add(name); } Collections.sort(osNotNull, new Comparator<String>() { @Override public int compare(String l, String r) { return r.length() - l.length(); } }); } } #8 Kotlin - Using collections http://kotlinlang.org/docs/reference/basic-syntax.html#using-collections vs
  • 23. fun example() { val os = listOf("Android", "iOS", null, "Windows Phone") os.filterNotNull().sortedBy { it.length() } .map { it.toUpperCase() } } class MyUtils { static void example() { List<String> os = Arrays.asList("Android", "iOS", null, "Windows Phone"); List<String> osNotNull = new ArrayList<>(); for (String name : os) { if (name != null) osNotNull.add(name); } Collections.sort(osNotNull, new Comparator<String>() { @Override public int compare(String l, String r) { return l.length() - r.length(); } }); for (String name : osNotNull) { String value = name.toUpperCase(); } } } #8 Kotlin - Using collections http://kotlinlang.org/docs/reference/basic-syntax.html#using-collections vs
  • 24. fun example() { val os = listOf("Android", "iOS", null, "Windows Phone") os.filterNotNull().sortedBy { it.length() } .map { it.toUpperCase() } .forEach { print(it) } } class MyUtils { static void example() { List<String> os = Arrays.asList("Android", "iOS", null, "Windows Phone"); List<String> osNotNull = new ArrayList<>(); for (String name : os) { if (name != null) osNotNull.add(name); } Collections.sort(osNotNull, new Comparator<String>() { @Override public int compare(String l, String r) { return l.length() - r.length(); } }); for (String name : osNotNull) { String value = name.toUpperCase(); print(value); } } } #8 Kotlin - Using collections http://kotlinlang.org/docs/reference/basic-syntax.html#using-collections vs
  • 25. Android Example From Java to Kotlin! https://github.com/jacklt/KotlinExample/tree/ex1
  • 26. dummy/Items.kt data class HeroItem(val name: String, val gender: String, val power: Int)
  • 27. dummy/HeroDummyContent.kt object HeroDummyContent { private val MALE = "Male" private val FEMALE = "Female" val ITEMS = listOf( HeroItem("Hulk", MALE, 9), HeroItem("Iron Man", MALE, 8), HeroItem("Thor", MALE, 8), HeroItem("Jessica Jones", FEMALE, 2), HeroItem("Spiderman", MALE, 4) ) }
  • 28. dummy/HeroDummyContent.kt > object vs class object HeroDummyContent { private val MALE = "Male" private val FEMALE = "Female" val ITEMS = listOf( HeroItem("Hulk", MALE, 9), HeroItem("Iron Man", MALE, 8), HeroItem("Thor", MALE, 8), HeroItem("Jessica Jones", FEMALE, 2), HeroItem("Spiderman", MALE, 4) ) }
  • 29. dummy/HeroDummyContent.kt > listOf(...) object HeroDummyContent { private val MALE = "Male" private val FEMALE = "Female" val ITEMS = listOf( HeroItem("Hulk", MALE, 9), HeroItem("Iron Man", MALE, 8), HeroItem("Thor", MALE, 8), HeroItem("Jessica Jones", FEMALE, 2), HeroItem("Spiderman", MALE, 4) ) }
  • 30. dummy/HeroAdapter.kt class HeroAdapter(val mValues: List<HeroItem>, val mListener: Function1<HeroItem, Unit>?) : RecyclerView.Adapter<HeroAdapter.ViewHolder>() { // ... override fun onBindViewHolder(holder: ViewHolder, position: Int) { val hero = mValues[position] holder.item = hero holder.nameView.text = "${hero.name} (Power: ${hero.power})" holder.genderView.text = hero.gender holder.itemView.setOnClickListener { mListener?.invoke(hero) } } // ... }
  • 31. dummy/HeroAdapter.kt > String template class HeroAdapter(val mValues: List<HeroItem>, val mListener: Function1<HeroItem, Unit>?) : RecyclerView.Adapter<HeroAdapter.ViewHolder>() { // ... override fun onBindViewHolder(holder: ViewHolder, position: Int) { val hero = mValues[position] holder.item = hero holder.nameView.text = "${hero.name} (Power: ${hero.power})" holder.genderView.text = hero.gender holder.itemView.setOnClickListener { mListener?.invoke(hero) } } // ... }
  • 32. MainActivity.kt class MainActivity : AppCompatActivity() { private var currentHero: HeroItem? = null private val adapter by lazy { HeroAdapter(HeroDummyContent.ITEMS) { // onItemClick ... } } // ... }
  • 33. MainActivity.kt > adapter (lazy) HeroAdapter(HeroDummyContent.ITEMS) { // onClick val previousHero = currentHero if (previousHero != null) { // fight val conclusion = if (previousHero.power == it.power) { "It's a draw" } else if (previousHero.power > it.power) { "${previousHero.name} wins!" } else { "${it.name} wins!" } Snackbar.make(fab, "${previousHero.name} vs ${it.name}!n$conclusion", Snackbar.LENGTH_LONG).show() currentHero = null } else { // assign current hero Snackbar.make(fab, "Choose: ${it.name}", Snackbar.LENGTH_SHORT).show() currentHero = it } }
  • 34. MainActivity.kt > adapter (lazy) > Smart cast HeroAdapter(HeroDummyContent.ITEMS) { // onClick val previousHero = currentHero if (previousHero != null) { // fight val conclusion = if (previousHero.power == it.power) { "It's a draw" } else if (previousHero.power > it.power) { "${previousHero.name} wins!" } else { "${it.name} wins!" } Snackbar.make(fab, "${previousHero.name} vs ${it.name}!n$conclusion", Snackbar.LENGTH_LONG).show() currentHero = null } else { // assign current hero Snackbar.make(fab, "Choose: ${it.name}", Snackbar.LENGTH_SHORT).show() currentHero = it } }
  • 35. MainActivity.kt > adapter (lazy) > return if expression HeroAdapter(HeroDummyContent.ITEMS) { // onClick val previousHero = currentHero if (previousHero != null) { // fight val conclusion = if (previousHero.power == it.power) { "It's a draw" } else if (previousHero.power > it.power) { "${previousHero.name} wins!" } else { "${it.name} wins!" } Snackbar.make(fab, "${previousHero.name} vs ${it.name}!n$conclusion", Snackbar.LENGTH_LONG).show() currentHero = null } else { // assign current hero Snackbar.make(fab, "Choose: ${it.name}", Snackbar.LENGTH_SHORT).show() currentHero = it } }
  • 36. Questions? Developers playground - #EX2 - Aggiungere le proprietà a HeroItem: hair (String?), eyes (String?) - Mostrarle (se presenti) nella lista - Se vengono scelti 2 eroi di sesso opposto, viene creato un nuovo eroe - Si possono usare le proprietà dei genitori, oppure dei valori di default se mancano Start with: https://github.com/jacklt/KotlinExample/tree/ex1 Solution: https://github.com/jacklt/KotlinExample/tree/ex2
  • 37. THANKS! Omar Miatello, Member of GDG Milano (Italy) Android Developer @ Satispay