SlideShare a Scribd company logo
// Java
@Override
public int getItemCount() {
return mItems != null ? mItems.size() : 0;
}
// Kotlin
override fun getItemCount() = items.size
Swift
~
// Java
button.setOnClickListener({
@Override
public void onClick(View v) {
// Make it happen
}
});
// Kotlin
button.setOnClickListener {
// Make it happen
}
Java
Java
+
buildscript {
...
dependencies {
...
classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.30"
}
}
build.gradle in Project
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'
apply plugin: 'kotlin-kapt'
...
dependencies {
...
implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:1.2.40"
}
...
build.gradle in Module
// Read-write
var a: Int = 0
var b: String? = null
var c = "Kotlin"
var d = User()
lateinit var c: Int
// Read-only
val pi = 3.14
val d = User()
const val pi = 3.14
var b: String? = null
String? = String + null
Button button = findViewById(R.id.button);
button.setOnClickListener({
@Override
public void onClick(View v) {
// Make it happen
}
});
@BindView(R.id.button) Button button;
@OnClick(R.id.button) void clickTodoSth() {
// Make it happen
}
import kotlinx.android.synthetic.main.fragment_main.*
button.setOnClickListener {
// Make it happen
}
public class User {
private String name;
private int age;
public User(String n, int a) {
name = n;
age = a;
}
public int getName() {
return name;
}
public int getAge() {
return age;
}
}
class User(
val name: String,
val age: Int)
// Java
private static final String BUNDLE_GET_STRING =
"bundle:str";
public static SampleFragment newInstance(String name) {
SampleFragment fragment = new SampleFragment();
Bundle bundle = new Bundle();
bundle.putString(BUNDLE_GET_STRING name);
fragment.setArguments(bundle);
return fragment;
}
// Kotlin
companion object {
private const val BUNDLE_GET_STRING = "bundle:str"
fun newInstance(name: String?): SampleFragment {
val fragment = SampleFragment()
val bundle = Bundle()
bundle.putString(BUNDLE_GET_STRING, name)
fragment.arguments = bundle
return fragment
}
}
// Kotlin
if (savedInstanceState == null) {
supportFragmentManager.beginTransaction().
replace(R.id. content, SampleFragment.newInstance( "Cherprang")).
commit()
}
// Java
public static SampleFragment newInstance() {
SampleFragment fragment = new SampleFragment();
return fragment;
}
// Kotlin
fun newInstance() = SampleFragment()
// Java
public boolean getIsLogin() {
return preferences.getBoolean(PREFERENCE_KEY_IS_LOGIN, false);
}
public void setIsLogin(boolean isLogin) {
editor.putBoolean(PREFERENCE_KEY_IS_LOGIN, isLogin);
editor.commit();
}
// Kotlin
var isLogin: Boolean
get() = preferences.getBoolean(PREFERENCE_KEY_IS_LOGIN, false)
set(value) {
editor.putBoolean(PREFERENCE_KEY_IS_LOGIN, value)
editor.commit()
}
// Java
class SomethingInTheApp {
public SomethingInTheApp(Context context) {
this.mContext = context;
}
...
}
// Kotlin
class SomethingInTheApp {
constructor(context: Context) {
this.mContext = context
}
…
}
// Kotlin
class SomethingInTheApp(context: Context) {
private var mContext = context
…
}
// Java
public class AnimationView extends LinearLayout {
...
public AnimationView(Context context) {
super(context);
...
}
public AnimationView(Context context , AttributeSet attrs) {
super(context, attrs);
...
}
...
}
// Kotlin
class AnimationView: LinearLayout {
constructor(context: Context) : super(context) {
initialize(context)
...
}
constructor(context: Context , attrs: AttributeSet) : super(context, attrs)
{
initialize(context)
...
}
...
}
// Kotlin
class AnimationView: LinearLayout {
constructor(context: Context) : super(context) {
initialize(context)
...
}
}
// Kotlin
class AnimationView(context: Context): LinearLayout(context) {
init {
initialize(context)
...
}
}
open class BaseFragment : Fragment() {
...
}
sealed class ProfileRouting: FuelRouting {
val PARAM_AUTH = "Authorization"
override val basePath: String
get() = Constant. BASE_PATH
class getProfile(val token: String): ProfileRouting() {
override val method: Method
get() = Method.GET
override val path: String
get() = "/users"
override val params: List<Pair<String , Any?>>?
get() = null
override val headers: Map<String, String>?
get() = null
}
}
data class UserProfile(
val id: String,
val name: String,
val age: Int,
val email: String
val pictureUrl: String)
// Java
Button button = findViewById(R.id.button);
button.setOnClickListener({
@Override
public void onClick(View v) {
// Make it happen
}
});
// Kotlin
button.setOnClickListener {
// Make it happen
}
// Java
new CountDownTimer( 30000, 1000) {
public void onTick(long millisUntilFinished) {
mTextField.setText( "seconds remaining: " + millisUntilFinished / 1000);
}
public void onFinish() {
mTextField.setText( "done!");
}
}.start();
// Kotlin
object : CountDownTimer( 30000, 1000) {
override fun onTick(millisUntilFinished: Long) {
mTextField.setText( "seconds remaining: " + millisUntilFinished / 1000)
}
override fun onFinish() {
mTextField.setText( "done!")
}
}.start()
Run fun <T, R> T.run(block: T.() -> R): R = block()
With fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block()
Apply fun <T> T.apply(block: T.() -> Unit): T = { block(); return this }Also
Also fun <T> T.also(block: (T) -> Unit): T = { block(this); return this }
Let fun <T, R> T.let(block: (T) -> R): R = block(this)
button.text = "Press This"
button.isClickable = true
button.background = resources.getDrawable(
R.drawable.green,
this.theme)
button.apply {
text = "Press This"
isClickable = true
background = resources.getDrawable(
R.drawable.green,
this.theme)
}
button.also {
it.text = "Press This"
it.isClickable = true
it.background = resources.getDrawable(
R.drawable.green,
this.theme)
}
button.apply {
text = "Press This"
isClickable = true
background = resources.getDrawable(
R.drawable.green,
this.theme)
}.also {
Toast.makeText(context, "gogo~”,
Toast.LENGTH_SHORT).show()
}
button.let {
it.text = "Press This"
it.isClickable = true
it.background = resources.getDrawable(
R.drawable.green,
this.theme)
}
if (player != null) {
playbackPosition = player!!.currentPosition
currentWindow = player!!.currentWindowIndex
playWhenReady = player!!.playWhenReady
player?.release()
player = null
}
player?.let {
playbackPosition = player!!.currentPosition
currentWindow = player!!.currentWindowIndex
playWhenReady = player!!.playWhenReady
player?.release()
player = null
}
edittext.apply {
text = "username"
...
}.run {
Toast.makeText(context, edittext.text.toString(),
Toast.LENGTH_SHORT).show()
}
// Kotlin
if (responseCode == 200OK) {
textResponse.text = "Successful!"
} else if (case == 401Unauthorized) {
textResponse.text = "Please log-in"
} else if (case == 404NotFound) {
textResponse.text = "cannot load data now"
} else if (case == 500ServerError) {
textResponse.text = "Internal Server Error"
}
// Kotlin
when (responseCode) {
200OK -> textResponse.text = "Successful!"
401Unauthorized -> textResponse.text = "Please log-in"
404NotFound -> textResponse.text = "cannot load data now"
500ServerError -> textResponse.text = "Internal Server Error"
}
// Java
itemSize = isTrue ? itemSize : 0;
// Kotlin
itemSize = if (isTrue) itemSize else 0
// Kotlin
print(company.department.employee.name)
// Safe call
print(company?.department?.employee?.name)
// Assertion
print(company!!.department.employee.name)
// Elvis operator
val s = str ?: ""
// Kotlin Loop
for (i in range) {
print (i)
}
val iterator = (1..3).iterator()
// skip an element
if (iterator.hasNext()) {
iterator.next()
}
// do something with the rest of elements
iterator.forEach {
println("The element is $it")
}
simpleList.forEachIndexed {
index, element -> println(
"index = $index, element = $element")
}
$
// Java
println("a = " + a + "b = " + b + "c = " + c)
// Kotlin
println("a = $a, b = $b, c = $c")
// Java
String[] member = {"Cherprang", "Music", "Pun", "Jennis"};
// Kotlin
var member = arrayOf("Cherprang", "Music", "Pun", "Jennis")
mapOf(KEY to "value")
listOf(KEY to "value")
// Java
array.get(0).count;
// Kotlin
array[0].count
// build.gradle
dependencies {
...
implementation 'com.github.kittinunf.fuel:fuel-android:1.12.0'
implementation 'com.github.kittinunf.fuel:fuel-gson:1.12.0'
}
sealed class ProfileRouting: FuelRouting {
val PARAM_AUTH = "Authorization"
override val basePath: String
get() = Constant.BASE_PATH
class getProfile(val token: String): ProfileRouting() {
override val method: Method
get() = Method.GET
override val path: String
get() = "/users"
override val params: List<Pair<String, Any?>>?
get() = null
override val headers: Map<String, String>?
get() = null
}
}
class ProfilePresenter(listener: UserProfileListener) {
private var mListener = listener
fun getProfile() {
Fuel.request(ProfileRouting.getProfile())
.responseObject(UserProfile.Deserializer()) {
_, _, result ->
result.fold( success = { userProfile ->
mListener.onProfileSuccess(userProfile)
}, failure = { error ->
mListener.onProfileFailure(error)
})
}
}
}
interface UserProfileListener {
fun onProfileSuccess(profile: Profile)
fun onProfileFailure(error: FuelError)
}
// Call this
ProfilePresenter(this).getUserProfile()
// handle listener
override fun onProfileSuccess(profile: UserProfile) {
//TODO: handle for success
}
override fun onProfileFailure(error: FuelError) {
//TODO: handle for success
}
#31DaysOfKotlin
Cheat Sheet?!
Songshakes, cover artist community, is coming soon!!

More Related Content

What's hot

Java libraries you can't afford to miss
Java libraries you can't afford to missJava libraries you can't afford to miss
Java libraries you can't afford to miss
Andres Almiray
 
Google guava
Google guavaGoogle guava
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
Mite Mitreski
 
Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03
Omar Miatello
 
Android & Kotlin - The code awakens #02
Android & Kotlin - The code awakens #02Android & Kotlin - The code awakens #02
Android & Kotlin - The code awakens #02
Omar Miatello
 
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
Anton Arhipov
 
Get started with YUI
Get started with YUIGet started with YUI
Get started with YUIAdam Lu
 
Kotlin - lo Swift di Android
Kotlin - lo Swift di AndroidKotlin - lo Swift di Android
Kotlin - lo Swift di Android
Omar Miatello
 
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
 
Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01
Omar Miatello
 
Dagger 2 vs koin
Dagger 2 vs koinDagger 2 vs koin
Dagger 2 vs koin
Jintin Lin
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Domenic Denicola
 
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
Anton Arhipov
 
Google Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantesmikaelbarbero
 
The core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaThe core libraries you always wanted - Google Guava
The core libraries you always wanted - Google Guava
Mite Mitreski
 
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
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife SpringMario Fusco
 
Java 8 Puzzlers [as presented at OSCON 2016]
Java 8 Puzzlers [as presented at  OSCON 2016]Java 8 Puzzlers [as presented at  OSCON 2016]
Java 8 Puzzlers [as presented at OSCON 2016]
Baruch Sadogursky
 
Akka tips
Akka tipsAkka tips
Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to know
Tomasz Dziurko
 

What's hot (20)

Java libraries you can't afford to miss
Java libraries you can't afford to missJava libraries you can't afford to miss
Java libraries you can't afford to miss
 
Google guava
Google guavaGoogle guava
Google guava
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner code
 
Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03
 
Android & Kotlin - The code awakens #02
Android & Kotlin - The code awakens #02Android & Kotlin - The code awakens #02
Android & Kotlin - The code awakens #02
 
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
 
Get started with YUI
Get started with YUIGet started with YUI
Get started with YUI
 
Kotlin - lo Swift di Android
Kotlin - lo Swift di AndroidKotlin - lo Swift di Android
Kotlin - lo Swift di Android
 
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
 
Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01
 
Dagger 2 vs koin
Dagger 2 vs koinDagger 2 vs koin
Dagger 2 vs koin
 
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
Callbacks, Promises, and Coroutines (oh my!): Asynchronous Programming Patter...
 
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
 
Google Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG NantesGoogle Guava & EMF @ GTUG Nantes
Google Guava & EMF @ GTUG Nantes
 
The core libraries you always wanted - Google Guava
The core libraries you always wanted - Google GuavaThe core libraries you always wanted - Google Guava
The core libraries you always wanted - Google Guava
 
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
 
Swiss army knife Spring
Swiss army knife SpringSwiss army knife Spring
Swiss army knife Spring
 
Java 8 Puzzlers [as presented at OSCON 2016]
Java 8 Puzzlers [as presented at  OSCON 2016]Java 8 Puzzlers [as presented at  OSCON 2016]
Java 8 Puzzlers [as presented at OSCON 2016]
 
Akka tips
Akka tipsAkka tips
Akka tips
 
Google guava - almost everything you need to know
Google guava - almost everything you need to knowGoogle guava - almost everything you need to know
Google guava - almost everything you need to know
 

Similar to Kotlin Generation

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
 
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
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
TechMagic
 
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
 
droidcon Transylvania - Kotlin Coroutines
droidcon Transylvania - Kotlin Coroutinesdroidcon Transylvania - Kotlin Coroutines
droidcon Transylvania - Kotlin Coroutines
Arthur Nagy
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
Shaul Rosenzwieg
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
Kurt Renzo Acosta
 
Kotlin on android
Kotlin on androidKotlin on android
Kotlin on android
Kurt Renzo Acosta
 
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
PROIDEA
 
つくってあそぼ Kotlin DSL ~拡張編~
つくってあそぼ Kotlin DSL ~拡張編~つくってあそぼ Kotlin DSL ~拡張編~
つくってあそぼ Kotlin DSL ~拡張編~
kamedon39
 
Kotlin
KotlinKotlin
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
VMware Tanzu
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
MobileAcademy
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
Andrew Dupont
 
Kotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan SoaresKotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan Soares
iMasters
 
Unit Testing in Kotlin
Unit Testing in KotlinUnit Testing in Kotlin
Unit Testing in Kotlin
Egor Andreevich
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
Artur Latoszewski
 
Kotlin/Everywhere GDG Bhubaneswar 2019
Kotlin/Everywhere GDG Bhubaneswar 2019 Kotlin/Everywhere GDG Bhubaneswar 2019
Kotlin/Everywhere GDG Bhubaneswar 2019
Sriyank Siddhartha
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
tdc-globalcode
 
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
 

Similar to Kotlin Generation (20)

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
 
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
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for Kotlin
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
 
droidcon Transylvania - Kotlin Coroutines
droidcon Transylvania - Kotlin Coroutinesdroidcon Transylvania - Kotlin Coroutines
droidcon Transylvania - Kotlin Coroutines
 
Introduction to kotlin
Introduction to kotlinIntroduction to kotlin
Introduction to kotlin
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with Android
 
Kotlin on android
Kotlin on androidKotlin on android
Kotlin on android
 
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
4Developers: Michał Szczepanik- Kotlin - Let’s ketchup it
 
つくってあそぼ Kotlin DSL ~拡張編~
つくってあそぼ Kotlin DSL ~拡張編~つくってあそぼ Kotlin DSL ~拡張編~
つくってあそぼ Kotlin DSL ~拡張編~
 
Kotlin
KotlinKotlin
Kotlin
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 Kotlin
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRready
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScript
 
Kotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan SoaresKotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan Soares
 
Unit Testing in Kotlin
Unit Testing in KotlinUnit Testing in Kotlin
Unit Testing in Kotlin
 
Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?Kotlin coroutine - the next step for RxJava developer?
Kotlin coroutine - the next step for RxJava developer?
 
Kotlin/Everywhere GDG Bhubaneswar 2019
Kotlin/Everywhere GDG Bhubaneswar 2019 Kotlin/Everywhere GDG Bhubaneswar 2019
Kotlin/Everywhere GDG Bhubaneswar 2019
 
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin WayTDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
TDC218SP | Trilha Kotlin - DSLs in a Kotlin Way
 
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
 

Recently uploaded

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
Alison B. Lowndes
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Jeffrey Haguewood
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
Sri Ambati
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Ramesh Iyer
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
Product School
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Thierry Lestable
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
James Anderson
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
Alan Dix
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
g2nightmarescribd
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Product School
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
Ana-Maria Mihalceanu
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
OnBoard
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
Jemma Hussein Allen
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
Product School
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
Product School
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Albert Hoitingh
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
91mobiles
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
Dorra BARTAGUIZ
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
Laura Byrne
 

Recently uploaded (20)

Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........Bits & Pixels using AI for Good.........
Bits & Pixels using AI for Good.........
 
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
Slack (or Teams) Automation for Bonterra Impact Management (fka Social Soluti...
 
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
GenAISummit 2024 May 28 Sri Ambati Keynote: AGI Belongs to The Community in O...
 
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
Builder.ai Founder Sachin Dev Duggal's Strategic Approach to Create an Innova...
 
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
AI for Every Business: Unlocking Your Product's Universal Potential by VP of ...
 
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
Empowering NextGen Mobility via Large Action Model Infrastructure (LAMI): pav...
 
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
GDG Cloud Southlake #33: Boule & Rebala: Effective AppSec in SDLC using Deplo...
 
Epistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI supportEpistemic Interaction - tuning interfaces to provide information for AI support
Epistemic Interaction - tuning interfaces to provide information for AI support
 
Generating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using SmithyGenerating a custom Ruby SDK for your web service or Rails API using Smithy
Generating a custom Ruby SDK for your web service or Rails API using Smithy
 
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdfFIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
FIDO Alliance Osaka Seminar: FIDO Security Aspects.pdf
 
Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...Designing Great Products: The Power of Design and Leadership by Chief Designe...
Designing Great Products: The Power of Design and Leadership by Chief Designe...
 
Monitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR EventsMonitoring Java Application Security with JDK Tools and JFR Events
Monitoring Java Application Security with JDK Tools and JFR Events
 
Leading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdfLeading Change strategies and insights for effective change management pdf 1.pdf
Leading Change strategies and insights for effective change management pdf 1.pdf
 
The Future of Platform Engineering
The Future of Platform EngineeringThe Future of Platform Engineering
The Future of Platform Engineering
 
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
From Siloed Products to Connected Ecosystem: Building a Sustainable and Scala...
 
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
De-mystifying Zero to One: Design Informed Techniques for Greenfield Innovati...
 
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
Encryption in Microsoft 365 - ExpertsLive Netherlands 2024
 
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdfSmart TV Buyer Insights Survey 2024 by 91mobiles.pdf
Smart TV Buyer Insights Survey 2024 by 91mobiles.pdf
 
Elevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object CalisthenicsElevating Tactical DDD Patterns Through Object Calisthenics
Elevating Tactical DDD Patterns Through Object Calisthenics
 
The Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and SalesThe Art of the Pitch: WordPress Relationships and Sales
The Art of the Pitch: WordPress Relationships and Sales
 

Kotlin Generation

  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14. // Java @Override public int getItemCount() { return mItems != null ? mItems.size() : 0; } // Kotlin override fun getItemCount() = items.size
  • 15.
  • 16.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22. // Java button.setOnClickListener({ @Override public void onClick(View v) { // Make it happen } }); // Kotlin button.setOnClickListener { // Make it happen }
  • 23. Java
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31. buildscript { ... dependencies { ... classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.2.30" } } build.gradle in Project
  • 32. apply plugin: 'kotlin-android' apply plugin: 'kotlin-android-extensions' apply plugin: 'kotlin-kapt' ... dependencies { ... implementation "org.jetbrains.kotlin:kotlin-stdlib-jre7:1.2.40" } ... build.gradle in Module
  • 33.
  • 34.
  • 35.
  • 36.
  • 37. // Read-write var a: Int = 0 var b: String? = null var c = "Kotlin" var d = User() lateinit var c: Int // Read-only val pi = 3.14 val d = User() const val pi = 3.14
  • 38. var b: String? = null String? = String + null
  • 39.
  • 40. Button button = findViewById(R.id.button); button.setOnClickListener({ @Override public void onClick(View v) { // Make it happen } });
  • 41. @BindView(R.id.button) Button button; @OnClick(R.id.button) void clickTodoSth() { // Make it happen }
  • 43. public class User { private String name; private int age; public User(String n, int a) { name = n; age = a; } public int getName() { return name; } public int getAge() { return age; } } class User( val name: String, val age: Int)
  • 44.
  • 45. // Java private static final String BUNDLE_GET_STRING = "bundle:str"; public static SampleFragment newInstance(String name) { SampleFragment fragment = new SampleFragment(); Bundle bundle = new Bundle(); bundle.putString(BUNDLE_GET_STRING name); fragment.setArguments(bundle); return fragment; }
  • 46. // Kotlin companion object { private const val BUNDLE_GET_STRING = "bundle:str" fun newInstance(name: String?): SampleFragment { val fragment = SampleFragment() val bundle = Bundle() bundle.putString(BUNDLE_GET_STRING, name) fragment.arguments = bundle return fragment } }
  • 47. // Kotlin if (savedInstanceState == null) { supportFragmentManager.beginTransaction(). replace(R.id. content, SampleFragment.newInstance( "Cherprang")). commit() }
  • 48. // Java public static SampleFragment newInstance() { SampleFragment fragment = new SampleFragment(); return fragment; } // Kotlin fun newInstance() = SampleFragment()
  • 49. // Java public boolean getIsLogin() { return preferences.getBoolean(PREFERENCE_KEY_IS_LOGIN, false); } public void setIsLogin(boolean isLogin) { editor.putBoolean(PREFERENCE_KEY_IS_LOGIN, isLogin); editor.commit(); }
  • 50. // Kotlin var isLogin: Boolean get() = preferences.getBoolean(PREFERENCE_KEY_IS_LOGIN, false) set(value) { editor.putBoolean(PREFERENCE_KEY_IS_LOGIN, value) editor.commit() }
  • 51.
  • 52. // Java class SomethingInTheApp { public SomethingInTheApp(Context context) { this.mContext = context; } ... }
  • 53. // Kotlin class SomethingInTheApp { constructor(context: Context) { this.mContext = context } … }
  • 54.
  • 55. // Kotlin class SomethingInTheApp(context: Context) { private var mContext = context … }
  • 56. // Java public class AnimationView extends LinearLayout { ... public AnimationView(Context context) { super(context); ... } public AnimationView(Context context , AttributeSet attrs) { super(context, attrs); ... } ... }
  • 57. // Kotlin class AnimationView: LinearLayout { constructor(context: Context) : super(context) { initialize(context) ... } constructor(context: Context , attrs: AttributeSet) : super(context, attrs) { initialize(context) ... } ... }
  • 58. // Kotlin class AnimationView: LinearLayout { constructor(context: Context) : super(context) { initialize(context) ... } }
  • 59. // Kotlin class AnimationView(context: Context): LinearLayout(context) { init { initialize(context) ... } }
  • 60.
  • 61. open class BaseFragment : Fragment() { ... }
  • 62. sealed class ProfileRouting: FuelRouting { val PARAM_AUTH = "Authorization" override val basePath: String get() = Constant. BASE_PATH class getProfile(val token: String): ProfileRouting() { override val method: Method get() = Method.GET override val path: String get() = "/users" override val params: List<Pair<String , Any?>>? get() = null override val headers: Map<String, String>? get() = null } }
  • 63. data class UserProfile( val id: String, val name: String, val age: Int, val email: String val pictureUrl: String)
  • 64. // Java Button button = findViewById(R.id.button); button.setOnClickListener({ @Override public void onClick(View v) { // Make it happen } });
  • 66. // Java new CountDownTimer( 30000, 1000) { public void onTick(long millisUntilFinished) { mTextField.setText( "seconds remaining: " + millisUntilFinished / 1000); } public void onFinish() { mTextField.setText( "done!"); } }.start();
  • 67. // Kotlin object : CountDownTimer( 30000, 1000) { override fun onTick(millisUntilFinished: Long) { mTextField.setText( "seconds remaining: " + millisUntilFinished / 1000) } override fun onFinish() { mTextField.setText( "done!") } }.start()
  • 68.
  • 69. Run fun <T, R> T.run(block: T.() -> R): R = block() With fun <T, R> with(receiver: T, block: T.() -> R): R = receiver.block() Apply fun <T> T.apply(block: T.() -> Unit): T = { block(); return this }Also Also fun <T> T.also(block: (T) -> Unit): T = { block(this); return this } Let fun <T, R> T.let(block: (T) -> R): R = block(this)
  • 70. button.text = "Press This" button.isClickable = true button.background = resources.getDrawable( R.drawable.green, this.theme)
  • 71. button.apply { text = "Press This" isClickable = true background = resources.getDrawable( R.drawable.green, this.theme) }
  • 72. button.also { it.text = "Press This" it.isClickable = true it.background = resources.getDrawable( R.drawable.green, this.theme) }
  • 73. button.apply { text = "Press This" isClickable = true background = resources.getDrawable( R.drawable.green, this.theme) }.also { Toast.makeText(context, "gogo~”, Toast.LENGTH_SHORT).show() }
  • 74. button.let { it.text = "Press This" it.isClickable = true it.background = resources.getDrawable( R.drawable.green, this.theme) }
  • 75. if (player != null) { playbackPosition = player!!.currentPosition currentWindow = player!!.currentWindowIndex playWhenReady = player!!.playWhenReady player?.release() player = null }
  • 76. player?.let { playbackPosition = player!!.currentPosition currentWindow = player!!.currentWindowIndex playWhenReady = player!!.playWhenReady player?.release() player = null }
  • 77.
  • 78. edittext.apply { text = "username" ... }.run { Toast.makeText(context, edittext.text.toString(), Toast.LENGTH_SHORT).show() }
  • 79. // Kotlin if (responseCode == 200OK) { textResponse.text = "Successful!" } else if (case == 401Unauthorized) { textResponse.text = "Please log-in" } else if (case == 404NotFound) { textResponse.text = "cannot load data now" } else if (case == 500ServerError) { textResponse.text = "Internal Server Error" }
  • 80. // Kotlin when (responseCode) { 200OK -> textResponse.text = "Successful!" 401Unauthorized -> textResponse.text = "Please log-in" 404NotFound -> textResponse.text = "cannot load data now" 500ServerError -> textResponse.text = "Internal Server Error" }
  • 81. // Java itemSize = isTrue ? itemSize : 0; // Kotlin itemSize = if (isTrue) itemSize else 0
  • 82.
  • 83. // Kotlin print(company.department.employee.name) // Safe call print(company?.department?.employee?.name) // Assertion print(company!!.department.employee.name)
  • 84. // Elvis operator val s = str ?: ""
  • 85. // Kotlin Loop for (i in range) { print (i) }
  • 86. val iterator = (1..3).iterator() // skip an element if (iterator.hasNext()) { iterator.next() } // do something with the rest of elements iterator.forEach { println("The element is $it") }
  • 87. simpleList.forEachIndexed { index, element -> println( "index = $index, element = $element") }
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93. $ // Java println("a = " + a + "b = " + b + "c = " + c) // Kotlin println("a = $a, b = $b, c = $c")
  • 94. // Java String[] member = {"Cherprang", "Music", "Pun", "Jennis"}; // Kotlin var member = arrayOf("Cherprang", "Music", "Pun", "Jennis") mapOf(KEY to "value") listOf(KEY to "value")
  • 96.
  • 97.
  • 98. // build.gradle dependencies { ... implementation 'com.github.kittinunf.fuel:fuel-android:1.12.0' implementation 'com.github.kittinunf.fuel:fuel-gson:1.12.0' }
  • 99.
  • 100. sealed class ProfileRouting: FuelRouting { val PARAM_AUTH = "Authorization" override val basePath: String get() = Constant.BASE_PATH class getProfile(val token: String): ProfileRouting() { override val method: Method get() = Method.GET override val path: String get() = "/users" override val params: List<Pair<String, Any?>>? get() = null override val headers: Map<String, String>? get() = null } }
  • 101. class ProfilePresenter(listener: UserProfileListener) { private var mListener = listener fun getProfile() { Fuel.request(ProfileRouting.getProfile()) .responseObject(UserProfile.Deserializer()) { _, _, result -> result.fold( success = { userProfile -> mListener.onProfileSuccess(userProfile) }, failure = { error -> mListener.onProfileFailure(error) }) } } }
  • 102. interface UserProfileListener { fun onProfileSuccess(profile: Profile) fun onProfileFailure(error: FuelError) }
  • 103. // Call this ProfilePresenter(this).getUserProfile() // handle listener override fun onProfileSuccess(profile: UserProfile) { //TODO: handle for success } override fun onProfileFailure(error: FuelError) { //TODO: handle for success }
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 117.
  • 118.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125. Songshakes, cover artist community, is coming soon!!