SlideShare a Scribd company logo
1 of 47
Android & Kotlin
The code awakens #01
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
What is Kotlin?
Statically typed programming language for the JVM, Android and the browser.
(http://kotlinlang.org/)
Why Kotlin?
Concise: drastically reduce the amount of boilerplate code you need to write.
Safe: avoid entire classes of errors such as null pointer exceptions.
Interoperable: leverage existing frameworks and libraries of the JVM with 100% Java
Interoperability.
and more... http://kotlinlang.org/docs/reference/comparison-to-java.html
Kotlin vs Java - Part 1
Property
String templates
Lambdas
Lazy properties
vs
public class MyKotlinClass {
val a: Int = 1
}
public class MyJavaClass {
private final int a = 1;
public int getA() {
return a;
}
}
#1 Kotlin - Properties: val, var
http://kotlinlang.org/docs/reference/properties.html
public class MyKotlinClass {
val a: Int = 1
var b: Int = 1
}
public class MyJavaClass {
private final int a = 1;
private int b = 1;
public int getA() {
return a;
}
public int getB() {
return b;
}
public void setB(int b) {
this.b = b;
}
}
#1 Kotlin - Properties: val, var
http://kotlinlang.org/docs/reference/properties.html
vs
public class MyKotlinClass {
val a: Int = 1
var b: Int = 1
val c = 1
var d = 1
}
public class MyJavaClass {
private final int a = 1;
private int b = 1;
private final int c = 1;
private int d = 1;
public int getA() { return a; }
public int getB() { return b; }
public void setB(int b) { this.b = b; }
public int getC() { return c; }
public int getD() { return d; }
public void setD(int d) { this.d = d; }
}
#1 Kotlin - Properties: val, var
http://kotlinlang.org/docs/reference/properties.html
vs
class MyKotlinClass {
val name = "Omar"
val surname = "Miatello"
}
class MyJavaClass {
final String getName() {
return "Omar";
}
final String getSurname() {
return "Miatello";
}
}
#2 Kotlin - String templates
http://kotlinlang.org/docs/reference/basic-syntax.html#using-string-templates
vs
class MyKotlinClass {
val name = "Omar"
val surname = "Miatello"
val example = "My name is $name $surname"
}
class MyJavaClass {
final String getName() {
return "Omar";
}
final String getSurname() {
return "Miatello";
}
final String getExample() {
return String.format("My name is %s %s",
getName(), getSurname()); }
}
#2 Kotlin - String templates
http://kotlinlang.org/docs/reference/basic-syntax.html#using-string-templates
vs
class MyKotlinClass {
val name = "Omar"
val surname = "Miatello"
val example = "My name is $name $surname"
}
class MyJavaClass {
final String getName() {
return "Omar";
}
final String getSurname() {
return "Miatello";
}
final String getExample() {
return String.format("My name is %s %s",
getName(), getSurname()); }
}
#2 Kotlin - String templates
http://kotlinlang.org/docs/reference/basic-syntax.html#using-string-templates
vs
class MyActivity : Activity() {
fun example() {
val view = findViewById(R.id.button)
view.setOnClickListener {
}
}
}
class MyActivity extends Activity {
void example() {
View view = findViewById(R.id.button);
view.setOnClickListener(
);
}
}
#3 Kotlin - Lambdas
http://kotlinlang.org/docs/reference/coding-conventions.html#lambdas
vs
class MyActivity : Activity() {
fun example() {
val view = findViewById(R.id.button)
view.setOnClickListener {
Log.d("TAG", "Item clicked!")
}
}
}
class MyActivity extends Activity {
void example() {
View view = findViewById(R.id.button);
view.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("TAG", "Item clicked!");
}
}
);
}
}
#3 Kotlin - Lambdas
http://kotlinlang.org/docs/reference/coding-conventions.html#lambdas
vs
class MyActivity : Activity() {
fun example() {
val view = findViewById(R.id.button)
view.setOnClickListener {
Log.d("TAG", "Item clicked!")
}
}
}
class MyActivity extends Activity {
void example() {
View view = findViewById(R.id.button);
view.setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.d("TAG", "Item clicked!");
}
}
);
}
}
#3 Kotlin - Lambdas
http://kotlinlang.org/docs/reference/coding-conventions.html#lambdas
vs
class MyJavaClass {
class MyItem { }
MyItem item;
}
#4 Kotlin - Delegated Properties: lazy (as example)
http://kotlinlang.org/docs/reference/delegated-properties.html
vs
class MyJavaClass {
class MyItem { }
MyItem item;
final MyItem getItem() {
if (item == null) {
item = new MyItem();
}
return item;
}
}
#4 Kotlin - Delegated Properties: lazy (as example)
http://kotlinlang.org/docs/reference/delegated-properties.html
vs
class MyItem
class MyKotlinClass {
val item by lazy { MyItem() }
}
// Simplified: in Kotlin is synchronized
class MyJavaClass {
class MyItem { }
MyItem item;
final MyItem getItem() {
if (item == null) {
item = new MyItem();
}
return item;
}
}
#4 Kotlin - Delegated Properties: lazy (as example)
http://kotlinlang.org/docs/reference/delegated-properties.html
vs
Install Kotlin in Android Studio
Part 1 / 2
1. Open “Preferences”
Install Kotlin in Android Studio
1. Open “Preferences”
2. Choose “Plugins” and “Install
JetBrains plugin…”
Install Kotlin in Android Studio
1. Open “Preferences”
2. Choose “Plugins” and “Install
JetBrains plugin…”
3. Install “Kotlin” and “Kotlin
Extensions For Android”
Install Kotlin in Android Studio
1. Open “Preferences”
2. Choose “Plugins” and “Install
JetBrains plugin…”
3. Install “Kotlin” and “Kotlin
Extensions For Android”
4. Restart Android Studio, and
open (or create) a project
Install Kotlin in Android Studio
1. Open “Preferences”
2. Choose “Plugins” and “Install
JetBrains plugin…”
3. Install “Kotlin” and “Kotlin
Extensions For Android”
4. Restart Android Studio, and
open (or create) a project
5. Create a new “Kotlin class”
Install Kotlin in Android Studio
Android Example
From Java to Kotlin! (step1)
https://github.com/jacklt/KotlinExample/tree/java-version
dummy/HeroItem.java
public class HeroItem {
public final String id;
public final String content;
public final String details;
public HeroItem(String id, String content, String details) {
this.id = id;
this.content = content;
this.details = details;
}
@Override
public String toString() {
return content;
}
}
dummy/HeroItem.java
public class HeroItem {
public final String id;
public final String content;
public final String details;
public HeroItem(String id, String content, String details) {
this.id = id;
this.content = content;
this.details = details;
}
@Override
public String toString() {
return content;
}
}
“Convert Java File to Kotlin File”
CTRL + ALT + SHIFT + K
(or CMD + ALT + SHIFT + K)
dummy/HeroItem.kt
class HeroItem(val id: String, val content: String, val details: String) {
override fun toString(): String {
return content
}
}
dummy/HeroItem.kt (optimized)
data class HeroItem(val id: String, val content: String, val details: String)
dummy/Items.kt (... a new hope)
data class HeroItem(val id: String, val content: String, val details: String)
data class VillanItem(val name: String, val power: String)
data class SpacecraftItem(val armaments: String, val defenses: String)
data class TinyItem(val name: String)
// ...
dummy/HeroAdapter.java (before HeroItem Conversion)
public class HeroAdapter extends RecyclerView.Adapter<HeroAdapter.ViewHolder> {
// ...
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
HeroItem item = mValues.get(position);
holder.item = item;
holder.idView.setText(item.id);
holder.contentView.setText(item.content);
// ...
}
// ...
}
dummy/HeroAdapter.java (after HeroItem Conversion)
public class HeroAdapter extends RecyclerView.Adapter<HeroAdapter.ViewHolder> {
// ...
@Override
public void onBindViewHolder(final ViewHolder holder, int position) {
HeroItem item = mValues.get(position);
holder.item = item;
holder.idView.setText(item.getId());
holder.contentView.setText(item.getContent());
// ...
}
// ...
}
Install Kotlin in Android Studio
Part 2 / 2
1. Open “Preferences”
2. Choose “Plugins” and “Install
JetBrains plugin…”
3. Install “Kotlin” and “Kotlin
Extensions For Android”
4. Restart Android Studio, and
open (or create) a project
5. Create a new “Kotlin class”
6. Choose from menu “Tools” >
“Kotlin” > “Configure Kotlin in
Project”
Install Kotlin in Android Studio
1. Open “Preferences”
2. Choose “Plugins” and “Install
JetBrains plugin…”
3. Install “Kotlin” and “Kotlin
Extensions For Android”
4. Restart Android Studio, and
open (or create) a project
5. Create a new “Kotlin class”
6. Choose from menu “Tools” >
“Kotlin” > “Configure Kotlin in
Project”
dependencies {
// other dependencies ...
compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version"
}
buildscript {
ext.kotlin_version = '1.0.0-beta-2423'
repositories {
mavenCentral()
}
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
}
}
repositories {
mavenCentral()
}
Install Kotlin in Android Studio
Android Example
From Java to Kotlin! (step2)
HeroAdapter
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)
dummy/HeroAdapter.kt (need manual fix)
// ...
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val idView: TextView
val contentView: TextView
var item: HeroItem
init {
idView = view.findViewById(R.id.id) as TextView
contentView = view.findViewById(R.id.content) as TextView
}
}
// ...
dummy/HeroAdapter.kt (fixed!)
// ...
inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) {
val idView: TextView
val contentView: TextView
var item: HeroItem? = null
init {
idView = view.findViewById(R.id.id) as TextView
contentView = view.findViewById(R.id.content) as TextView
}
}
// ...
dummy/HeroAdapter.kt (optimized)
// OPTIMIZATION 1: In class constructor
val mListener: HeroOnClickListener?
// can be replaced with
val mListener: Function1<HeroItem, Unit>?
// OPTIMIZATION 2: Method definition
override fun getItemCount(): Int {
return mValues.size
}
// can be replaced with
override fun getItemCount() = mValues.size
Android Example
From Java to Kotlin! (step3)
MainActivity
with Kotlin Android Extension
build.gradle (add kotlin-android-extensions)
// ..
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
}
// ..
build.gradle (add kotlin-android-extensions)
// ..
dependencies {
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version"
}
// ..
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Toolbar toolbar;
private FloatingActionButton fab;
private RecyclerView recyclerView;
private HeroAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG)
“Convert Java File to Kotlin File”
CTRL + ALT + SHIFT + K
(or CMD + ALT + SHIFT + K)
MainActivity.kt (optimized, add import)
import kotlinx.android.synthetic.activity_main.*
MainActivity.kt (optimized, use lazy for adapter)
import kotlinx.android.synthetic.activity_main.*
class MainActivity : AppCompatActivity() {
private val adapter by lazy {
HeroAdapter(HeroDummyContent.ITEMS) { Snackbar.make(fab, "Tap on: " + it, Snackbar.LENGTH_SHORT).show() }
}
MainActivity.kt (optimized, remove all unused property)
import kotlinx.android.synthetic.activity_main.*
class MainActivity : AppCompatActivity() {
private val adapter by lazy {
HeroAdapter(HeroDummyContent.ITEMS) { Snackbar.make(fab, "Tap on: " + it, Snackbar.LENGTH_SHORT).show() }
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
setSupportActionBar(toolbar)
fab.setOnClickListener { Snackbar.make(it, "...", Snackbar.LENGTH_LONG).setAction("Action", null).show() }
recyclerView.layoutManager = LinearLayoutManager(this)
recyclerView.adapter = adapter
}
}
Questions?
Developers playground - #EX1
- Add properties to HeroItem: name, gender (String), power (Int)
- Show item in list like: “$name (Power: $power)”
- Choose (and keep in memory) hero “onClick”
- Fight with second “onClick” (show a Snackbar)
Hint: Add in MainActivity “selectedHero” property (in Kotlin, or use field in Java)
Start with: https://github.com/jacklt/KotlinExample/tree/java-version or https://github.com/jacklt/KotlinExample/tree/kotlin-
version
Solution: https://github.com/jacklt/KotlinExample/tree/ex1
THANKS!
Omar Miatello, Member of GDG Milano (Italy)
Android Developer @ Satispay

More Related Content

What's hot

Kotlin: lo Swift di Android (2015)
Kotlin: lo Swift di Android (2015)Kotlin: lo Swift di Android (2015)
Kotlin: lo Swift di Android (2015)Omar Miatello
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenPawel Szulc
 
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
 
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
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleAnton Arhipov
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationIvan Dolgushin
 
Ast transformations
Ast transformationsAst transformations
Ast transformationsHamletDRC
 
AST Transformations
AST TransformationsAST Transformations
AST TransformationsHamletDRC
 
Real world gobbledygook
Real world gobbledygookReal world gobbledygook
Real world gobbledygookPawel Szulc
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistAnton Arhipov
 
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingRiga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingAnton 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 confIgor Anishchenko
 
Letswift Swift 3.0
Letswift Swift 3.0Letswift Swift 3.0
Letswift Swift 3.0Sehyun Park
 

What's hot (20)

Kotlin: lo Swift di Android (2015)
Kotlin: lo Swift di Android (2015)Kotlin: lo Swift di Android (2015)
Kotlin: lo Swift di Android (2015)
 
Functional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heavenFunctional Programming & Event Sourcing - a pair made in heaven
Functional Programming & Event Sourcing - a pair made in heaven
 
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
 
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
 
GeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassleGeeCON 2017 - TestContainers. Integration testing without the hassle
GeeCON 2017 - TestContainers. Integration testing without the hassle
 
EMF Tips n Tricks
EMF Tips n TricksEMF Tips n Tricks
EMF Tips n Tricks
 
Using Reflections and Automatic Code Generation
Using Reflections and Automatic Code GenerationUsing Reflections and Automatic Code Generation
Using Reflections and Automatic Code Generation
 
Ast transformations
Ast transformationsAst transformations
Ast transformations
 
AST Transformations
AST TransformationsAST Transformations
AST Transformations
 
Real world gobbledygook
Real world gobbledygookReal world gobbledygook
Real world gobbledygook
 
Mastering Java ByteCode
Mastering Java ByteCodeMastering Java ByteCode
Mastering Java ByteCode
 
Kotlin Generation
Kotlin GenerationKotlin Generation
Kotlin Generation
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
 
The Xtext Grammar Language
The Xtext Grammar LanguageThe Xtext Grammar Language
The Xtext Grammar Language
 
Kotlin
KotlinKotlin
Kotlin
 
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloadingRiga DevDays 2017 - The hitchhiker’s guide to Java class reloading
Riga DevDays 2017 - The hitchhiker’s guide to Java class reloading
 
Java Full Throttle
Java Full ThrottleJava Full Throttle
Java Full Throttle
 
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
 
Letswift Swift 3.0
Letswift Swift 3.0Letswift Swift 3.0
Letswift Swift 3.0
 

Viewers also liked

Exploring Anko Components, Kotlin, Android
Exploring Anko Components, Kotlin, AndroidExploring Anko Components, Kotlin, Android
Exploring Anko Components, Kotlin, AndroidRakshak R.Hegde
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLsintelliyole
 
Getting started-kotlin-android
Getting started-kotlin-androidGetting started-kotlin-android
Getting started-kotlin-androidLucas Albuquerque
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlinThijs Suijten
 
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)

Exploring Anko Components, Kotlin, Android
Exploring Anko Components, Kotlin, AndroidExploring Anko Components, Kotlin, Android
Exploring Anko Components, Kotlin, Android
 
Smoothing Your Java with DSLs
Smoothing Your Java with DSLsSmoothing Your Java with DSLs
Smoothing Your Java with DSLs
 
Getting started-kotlin-android
Getting started-kotlin-androidGetting started-kotlin-android
Getting started-kotlin-android
 
No excuses, switch to kotlin
No excuses, switch to kotlinNo excuses, switch to kotlin
No excuses, switch to kotlin
 
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 #01

Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyMobileAcademy
 
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 SurabayaDILo Surabaya
 
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna loveWriting Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna loveAndré Oriani
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseChristian Melchior
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014First Tuesday Bergen
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized projectFabio Collini
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to javaciklum_ods
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014Matthias Noback
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)Jose Manuel Pereira Garcia
 
Jeff English: Demystifying Module Development - How to Extend Titanium
Jeff English: Demystifying Module Development - How to Extend TitaniumJeff English: Demystifying Module Development - How to Extend Titanium
Jeff English: Demystifying Module Development - How to Extend TitaniumAxway Appcelerator
 
[2019] PAYCO 매거진 서버 Kotlin 적용기
[2019] PAYCO 매거진 서버 Kotlin 적용기[2019] PAYCO 매거진 서버 Kotlin 적용기
[2019] PAYCO 매거진 서버 Kotlin 적용기NHN FORWARD
 
Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFPierre-Yves Ricau
 
Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsHassan Abid
 
Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers STX Next
 
Kotlinでテストコードを書く
Kotlinでテストコードを書くKotlinでテストコードを書く
Kotlinでテストコードを書くShoichi Matsuda
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 KotlinVMware Tanzu
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Murat Yener
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumMatthias Noback
 

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

Koin Quickstart
Koin QuickstartKoin Quickstart
Koin Quickstart
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
 
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
 
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna loveWriting Kotlin Multiplatform libraries that your iOS teammates are gonna love
Writing Kotlin Multiplatform libraries that your iOS teammates are gonna love
 
Coroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in PractiseCoroutines for Kotlin Multiplatform in Practise
Coroutines for Kotlin Multiplatform in Practise
 
Dependency Injection for Android
Dependency Injection for AndroidDependency Injection for Android
Dependency Injection for Android
 
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
Dependency Injection for Android @ Ciklum speakers corner Kiev 29. May 2014
 
Using hilt in a modularized project
Using hilt in a modularized projectUsing hilt in a modularized project
Using hilt in a modularized project
 
Bring the fun back to java
Bring the fun back to javaBring the fun back to java
Bring the fun back to java
 
The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014The Naked Bundle - Symfony Live London 2014
The Naked Bundle - Symfony Live London 2014
 
From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)From Legacy to Hexagonal (An Unexpected Android Journey)
From Legacy to Hexagonal (An Unexpected Android Journey)
 
Jeff English: Demystifying Module Development - How to Extend Titanium
Jeff English: Demystifying Module Development - How to Extend TitaniumJeff English: Demystifying Module Development - How to Extend Titanium
Jeff English: Demystifying Module Development - How to Extend Titanium
 
[2019] PAYCO 매거진 서버 Kotlin 적용기
[2019] PAYCO 매거진 서버 Kotlin 적용기[2019] PAYCO 매거진 서버 Kotlin 적용기
[2019] PAYCO 매거진 서버 Kotlin 적용기
 
Sharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SFSharper Better Faster Dagger ‡ - Droidcon SF
Sharper Better Faster Dagger ‡ - Droidcon SF
 
Building Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture ComponentsBuilding Modern Apps using Android Architecture Components
Building Modern Apps using Android Architecture Components
 
Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers Kotlin Advanced - language reference for Android developers
Kotlin Advanced - language reference for Android developers
 
Kotlinでテストコードを書く
Kotlinでテストコードを書くKotlinでテストコードを書く
Kotlinでテストコードを書く
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
 
Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15Android and the Seven Dwarfs from Devox'15
Android and the Seven Dwarfs from Devox'15
 
The Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup BelgiumThe Naked Bundle - Symfony Usergroup Belgium
The Naked Bundle - Symfony Usergroup Belgium
 

Recently uploaded

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AIABDERRAOUF MEHENNI
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxbodapatigopi8531
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...MyIntelliSource, Inc.
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceanilsa9823
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Steffen Staab
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsJhone kinadey
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Modelsaagamshah0812
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...kellynguyen01
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...ICS
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionSolGuruz
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comFatema Valibhai
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdfWave PLM
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...OnePlan Solutions
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providermohitmore19
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerThousandEyes
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsAlberto González Trastoy
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 

Recently uploaded (20)

SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AISyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
SyndBuddy AI 2k Review 2024: Revolutionizing Content Syndication with AI
 
Hand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptxHand gesture recognition PROJECT PPT.pptx
Hand gesture recognition PROJECT PPT.pptx
 
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
Try MyIntelliAccount Cloud Accounting Software As A Service Solution Risk Fre...
 
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female serviceCALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
CALL ON ➥8923113531 🔝Call Girls Badshah Nagar Lucknow best Female service
 
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
Shapes for Sharing between Graph Data Spaces - and Epistemic Querying of RDF-...
 
Right Money Management App For Your Financial Goals
Right Money Management App For Your Financial GoalsRight Money Management App For Your Financial Goals
Right Money Management App For Your Financial Goals
 
Unlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language ModelsUnlocking the Future of AI Agents with Large Language Models
Unlocking the Future of AI Agents with Large Language Models
 
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
Short Story: Unveiling the Reasoning Abilities of Large Language Models by Ke...
 
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS LiveVip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
Vip Call Girls Noida ➡️ Delhi ➡️ 9999965857 No Advance 24HRS Live
 
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
The Real-World Challenges of Medical Device Cybersecurity- Mitigating Vulnera...
 
Diamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with PrecisionDiamond Application Development Crafting Solutions with Precision
Diamond Application Development Crafting Solutions with Precision
 
HR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.comHR Software Buyers Guide in 2024 - HRSoftware.com
HR Software Buyers Guide in 2024 - HRSoftware.com
 
5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf5 Signs You Need a Fashion PLM Software.pdf
5 Signs You Need a Fashion PLM Software.pdf
 
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
Tech Tuesday-Harness the Power of Effective Resource Planning with OnePlan’s ...
 
TECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service providerTECUNIQUE: Success Stories: IT Service provider
TECUNIQUE: Success Stories: IT Service provider
 
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected WorkerHow To Troubleshoot Collaboration Apps for the Modern Connected Worker
How To Troubleshoot Collaboration Apps for the Modern Connected Worker
 
Microsoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdfMicrosoft AI Transformation Partner Playbook.pdf
Microsoft AI Transformation Partner Playbook.pdf
 
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time ApplicationsUnveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
Unveiling the Tech Salsa of LAMs with Janus in Real-Time Applications
 
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICECHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
CHEAP Call Girls in Pushp Vihar (-DELHI )🔝 9953056974🔝(=)/CALL GIRLS SERVICE
 
Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 

Android & Kotlin - The code awakens #01

  • 1. Android & Kotlin The code awakens #01
  • 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. What is Kotlin? Statically typed programming language for the JVM, Android and the browser. (http://kotlinlang.org/) Why Kotlin? Concise: drastically reduce the amount of boilerplate code you need to write. Safe: avoid entire classes of errors such as null pointer exceptions. Interoperable: leverage existing frameworks and libraries of the JVM with 100% Java Interoperability. and more... http://kotlinlang.org/docs/reference/comparison-to-java.html
  • 4. Kotlin vs Java - Part 1 Property String templates Lambdas Lazy properties
  • 5. vs public class MyKotlinClass { val a: Int = 1 } public class MyJavaClass { private final int a = 1; public int getA() { return a; } } #1 Kotlin - Properties: val, var http://kotlinlang.org/docs/reference/properties.html
  • 6. public class MyKotlinClass { val a: Int = 1 var b: Int = 1 } public class MyJavaClass { private final int a = 1; private int b = 1; public int getA() { return a; } public int getB() { return b; } public void setB(int b) { this.b = b; } } #1 Kotlin - Properties: val, var http://kotlinlang.org/docs/reference/properties.html vs
  • 7. public class MyKotlinClass { val a: Int = 1 var b: Int = 1 val c = 1 var d = 1 } public class MyJavaClass { private final int a = 1; private int b = 1; private final int c = 1; private int d = 1; public int getA() { return a; } public int getB() { return b; } public void setB(int b) { this.b = b; } public int getC() { return c; } public int getD() { return d; } public void setD(int d) { this.d = d; } } #1 Kotlin - Properties: val, var http://kotlinlang.org/docs/reference/properties.html vs
  • 8. class MyKotlinClass { val name = "Omar" val surname = "Miatello" } class MyJavaClass { final String getName() { return "Omar"; } final String getSurname() { return "Miatello"; } } #2 Kotlin - String templates http://kotlinlang.org/docs/reference/basic-syntax.html#using-string-templates vs
  • 9. class MyKotlinClass { val name = "Omar" val surname = "Miatello" val example = "My name is $name $surname" } class MyJavaClass { final String getName() { return "Omar"; } final String getSurname() { return "Miatello"; } final String getExample() { return String.format("My name is %s %s", getName(), getSurname()); } } #2 Kotlin - String templates http://kotlinlang.org/docs/reference/basic-syntax.html#using-string-templates vs
  • 10. class MyKotlinClass { val name = "Omar" val surname = "Miatello" val example = "My name is $name $surname" } class MyJavaClass { final String getName() { return "Omar"; } final String getSurname() { return "Miatello"; } final String getExample() { return String.format("My name is %s %s", getName(), getSurname()); } } #2 Kotlin - String templates http://kotlinlang.org/docs/reference/basic-syntax.html#using-string-templates vs
  • 11. class MyActivity : Activity() { fun example() { val view = findViewById(R.id.button) view.setOnClickListener { } } } class MyActivity extends Activity { void example() { View view = findViewById(R.id.button); view.setOnClickListener( ); } } #3 Kotlin - Lambdas http://kotlinlang.org/docs/reference/coding-conventions.html#lambdas vs
  • 12. class MyActivity : Activity() { fun example() { val view = findViewById(R.id.button) view.setOnClickListener { Log.d("TAG", "Item clicked!") } } } class MyActivity extends Activity { void example() { View view = findViewById(R.id.button); view.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Log.d("TAG", "Item clicked!"); } } ); } } #3 Kotlin - Lambdas http://kotlinlang.org/docs/reference/coding-conventions.html#lambdas vs
  • 13. class MyActivity : Activity() { fun example() { val view = findViewById(R.id.button) view.setOnClickListener { Log.d("TAG", "Item clicked!") } } } class MyActivity extends Activity { void example() { View view = findViewById(R.id.button); view.setOnClickListener( new View.OnClickListener() { @Override public void onClick(View v) { Log.d("TAG", "Item clicked!"); } } ); } } #3 Kotlin - Lambdas http://kotlinlang.org/docs/reference/coding-conventions.html#lambdas vs
  • 14. class MyJavaClass { class MyItem { } MyItem item; } #4 Kotlin - Delegated Properties: lazy (as example) http://kotlinlang.org/docs/reference/delegated-properties.html vs
  • 15. class MyJavaClass { class MyItem { } MyItem item; final MyItem getItem() { if (item == null) { item = new MyItem(); } return item; } } #4 Kotlin - Delegated Properties: lazy (as example) http://kotlinlang.org/docs/reference/delegated-properties.html vs
  • 16. class MyItem class MyKotlinClass { val item by lazy { MyItem() } } // Simplified: in Kotlin is synchronized class MyJavaClass { class MyItem { } MyItem item; final MyItem getItem() { if (item == null) { item = new MyItem(); } return item; } } #4 Kotlin - Delegated Properties: lazy (as example) http://kotlinlang.org/docs/reference/delegated-properties.html vs
  • 17. Install Kotlin in Android Studio Part 1 / 2
  • 18. 1. Open “Preferences” Install Kotlin in Android Studio
  • 19. 1. Open “Preferences” 2. Choose “Plugins” and “Install JetBrains plugin…” Install Kotlin in Android Studio
  • 20. 1. Open “Preferences” 2. Choose “Plugins” and “Install JetBrains plugin…” 3. Install “Kotlin” and “Kotlin Extensions For Android” Install Kotlin in Android Studio
  • 21. 1. Open “Preferences” 2. Choose “Plugins” and “Install JetBrains plugin…” 3. Install “Kotlin” and “Kotlin Extensions For Android” 4. Restart Android Studio, and open (or create) a project Install Kotlin in Android Studio
  • 22. 1. Open “Preferences” 2. Choose “Plugins” and “Install JetBrains plugin…” 3. Install “Kotlin” and “Kotlin Extensions For Android” 4. Restart Android Studio, and open (or create) a project 5. Create a new “Kotlin class” Install Kotlin in Android Studio
  • 23. Android Example From Java to Kotlin! (step1) https://github.com/jacklt/KotlinExample/tree/java-version
  • 24. dummy/HeroItem.java public class HeroItem { public final String id; public final String content; public final String details; public HeroItem(String id, String content, String details) { this.id = id; this.content = content; this.details = details; } @Override public String toString() { return content; } }
  • 25. dummy/HeroItem.java public class HeroItem { public final String id; public final String content; public final String details; public HeroItem(String id, String content, String details) { this.id = id; this.content = content; this.details = details; } @Override public String toString() { return content; } } “Convert Java File to Kotlin File” CTRL + ALT + SHIFT + K (or CMD + ALT + SHIFT + K)
  • 26. dummy/HeroItem.kt class HeroItem(val id: String, val content: String, val details: String) { override fun toString(): String { return content } }
  • 27. dummy/HeroItem.kt (optimized) data class HeroItem(val id: String, val content: String, val details: String)
  • 28. dummy/Items.kt (... a new hope) data class HeroItem(val id: String, val content: String, val details: String) data class VillanItem(val name: String, val power: String) data class SpacecraftItem(val armaments: String, val defenses: String) data class TinyItem(val name: String) // ...
  • 29. dummy/HeroAdapter.java (before HeroItem Conversion) public class HeroAdapter extends RecyclerView.Adapter<HeroAdapter.ViewHolder> { // ... @Override public void onBindViewHolder(final ViewHolder holder, int position) { HeroItem item = mValues.get(position); holder.item = item; holder.idView.setText(item.id); holder.contentView.setText(item.content); // ... } // ... }
  • 30. dummy/HeroAdapter.java (after HeroItem Conversion) public class HeroAdapter extends RecyclerView.Adapter<HeroAdapter.ViewHolder> { // ... @Override public void onBindViewHolder(final ViewHolder holder, int position) { HeroItem item = mValues.get(position); holder.item = item; holder.idView.setText(item.getId()); holder.contentView.setText(item.getContent()); // ... } // ... }
  • 31. Install Kotlin in Android Studio Part 2 / 2
  • 32. 1. Open “Preferences” 2. Choose “Plugins” and “Install JetBrains plugin…” 3. Install “Kotlin” and “Kotlin Extensions For Android” 4. Restart Android Studio, and open (or create) a project 5. Create a new “Kotlin class” 6. Choose from menu “Tools” > “Kotlin” > “Configure Kotlin in Project” Install Kotlin in Android Studio
  • 33. 1. Open “Preferences” 2. Choose “Plugins” and “Install JetBrains plugin…” 3. Install “Kotlin” and “Kotlin Extensions For Android” 4. Restart Android Studio, and open (or create) a project 5. Create a new “Kotlin class” 6. Choose from menu “Tools” > “Kotlin” > “Configure Kotlin in Project” dependencies { // other dependencies ... compile "org.jetbrains.kotlin:kotlin-stdlib:$kotlin_version" } buildscript { ext.kotlin_version = '1.0.0-beta-2423' repositories { mavenCentral() } dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" } } repositories { mavenCentral() } Install Kotlin in Android Studio
  • 34. Android Example From Java to Kotlin! (step2) HeroAdapter
  • 35. 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)
  • 36. dummy/HeroAdapter.kt (need manual fix) // ... inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val idView: TextView val contentView: TextView var item: HeroItem init { idView = view.findViewById(R.id.id) as TextView contentView = view.findViewById(R.id.content) as TextView } } // ...
  • 37. dummy/HeroAdapter.kt (fixed!) // ... inner class ViewHolder(view: View) : RecyclerView.ViewHolder(view) { val idView: TextView val contentView: TextView var item: HeroItem? = null init { idView = view.findViewById(R.id.id) as TextView contentView = view.findViewById(R.id.content) as TextView } } // ...
  • 38. dummy/HeroAdapter.kt (optimized) // OPTIMIZATION 1: In class constructor val mListener: HeroOnClickListener? // can be replaced with val mListener: Function1<HeroItem, Unit>? // OPTIMIZATION 2: Method definition override fun getItemCount(): Int { return mValues.size } // can be replaced with override fun getItemCount() = mValues.size
  • 39. Android Example From Java to Kotlin! (step3) MainActivity with Kotlin Android Extension
  • 40. build.gradle (add kotlin-android-extensions) // .. dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version" } // ..
  • 41. build.gradle (add kotlin-android-extensions) // .. dependencies { classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version" classpath "org.jetbrains.kotlin:kotlin-android-extensions:$kotlin_version" } // ..
  • 42. MainActivity.java public class MainActivity extends AppCompatActivity { private Toolbar toolbar; private FloatingActionButton fab; private RecyclerView recyclerView; private HeroAdapter adapter; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); fab = (FloatingActionButton) findViewById(R.id.fab); fab.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { Snackbar.make(view, "Replace with your own action", Snackbar.LENGTH_LONG) “Convert Java File to Kotlin File” CTRL + ALT + SHIFT + K (or CMD + ALT + SHIFT + K)
  • 43. MainActivity.kt (optimized, add import) import kotlinx.android.synthetic.activity_main.*
  • 44. MainActivity.kt (optimized, use lazy for adapter) import kotlinx.android.synthetic.activity_main.* class MainActivity : AppCompatActivity() { private val adapter by lazy { HeroAdapter(HeroDummyContent.ITEMS) { Snackbar.make(fab, "Tap on: " + it, Snackbar.LENGTH_SHORT).show() } }
  • 45. MainActivity.kt (optimized, remove all unused property) import kotlinx.android.synthetic.activity_main.* class MainActivity : AppCompatActivity() { private val adapter by lazy { HeroAdapter(HeroDummyContent.ITEMS) { Snackbar.make(fab, "Tap on: " + it, Snackbar.LENGTH_SHORT).show() } } override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_main) setSupportActionBar(toolbar) fab.setOnClickListener { Snackbar.make(it, "...", Snackbar.LENGTH_LONG).setAction("Action", null).show() } recyclerView.layoutManager = LinearLayoutManager(this) recyclerView.adapter = adapter } }
  • 46. Questions? Developers playground - #EX1 - Add properties to HeroItem: name, gender (String), power (Int) - Show item in list like: “$name (Power: $power)” - Choose (and keep in memory) hero “onClick” - Fight with second “onClick” (show a Snackbar) Hint: Add in MainActivity “selectedHero” property (in Kotlin, or use field in Java) Start with: https://github.com/jacklt/KotlinExample/tree/java-version or https://github.com/jacklt/KotlinExample/tree/kotlin- version Solution: https://github.com/jacklt/KotlinExample/tree/ex1
  • 47. THANKS! Omar Miatello, Member of GDG Milano (Italy) Android Developer @ Satispay