SlideShare ist ein Scribd-Unternehmen logo
1 von 125
Downloaden Sie, um offline zu lesen
// 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!!

Weitere ähnliche Inhalte

Was ist angesagt?

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 missAndres Almiray
 
Google Guava for cleaner code
Google Guava for cleaner codeGoogle Guava for cleaner code
Google Guava for cleaner codeMite Mitreski
 
Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03Android & Kotlin - The code awakens #03
Android & Kotlin - The code awakens #03Omar Miatello
 
Android & Kotlin - The code awakens #02
Android & Kotlin - The code awakens #02Android & Kotlin - The code awakens #02
Android & Kotlin - The code awakens #02Omar 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 reloadingAnton 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 AndroidOmar 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 & AndroidJordi Gerona
 
Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01Android & Kotlin - The code awakens #01
Android & Kotlin - The code awakens #01Omar Miatello
 
Dagger 2 vs koin
Dagger 2 vs koinDagger 2 vs koin
Dagger 2 vs koinJintin 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 hassleAnton 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 GuavaMite 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 confIgor 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
 
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 knowTomasz Dziurko
 

Was ist angesagt? (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
 

Ähnlich wie 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 kotlinAdit 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 developmentAdit Lal
 
K is for Kotlin
K is for KotlinK is for Kotlin
K is for KotlinTechMagic
 
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018
Kotlin for Android Developers - Victor Kropp - Codemotion Rome 2018Codemotion
 
droidcon Transylvania - Kotlin Coroutines
droidcon Transylvania - Kotlin Coroutinesdroidcon Transylvania - Kotlin Coroutines
droidcon Transylvania - Kotlin CoroutinesArthur Nagy
 
Building Mobile Apps with Android
Building Mobile Apps with AndroidBuilding Mobile Apps with Android
Building Mobile Apps with AndroidKurt 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 itPROIDEA
 
つくってあそぼ Kotlin DSL ~拡張編~
つくってあそぼ Kotlin DSL ~拡張編~つくってあそぼ Kotlin DSL ~拡張編~
つくってあそぼ Kotlin DSL ~拡張編~kamedon39
 
Why Spring <3 Kotlin
Why Spring <3 KotlinWhy Spring <3 Kotlin
Why Spring <3 KotlinVMware Tanzu
 
Kotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyKotlin for Android - Vali Iorgu - mRready
Kotlin for Android - Vali Iorgu - mRreadyMobileAcademy
 
Writing Maintainable JavaScript
Writing Maintainable JavaScriptWriting Maintainable JavaScript
Writing Maintainable JavaScriptAndrew Dupont
 
Kotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan SoaresKotlin : Advanced Tricks - Ubiratan Soares
Kotlin : Advanced Tricks - Ubiratan SoaresiMasters
 
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 Waytdc-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
 

Ähnlich wie 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
 

Kürzlich hochgeladen

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...apidays
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Servicegiselly40
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityPrincipled Technologies
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024Results
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?Igalia
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxKatpro Technologies
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking MenDelhi Call girls
 

Kürzlich hochgeladen (20)

Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
Apidays Singapore 2024 - Building Digital Trust in a Digital Economy by Veron...
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
CNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of ServiceCNv6 Instructor Chapter 6 Quality of Service
CNv6 Instructor Chapter 6 Quality of Service
 
Boost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivityBoost PC performance: How more available memory can improve productivity
Boost PC performance: How more available memory can improve productivity
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024A Call to Action for Generative AI in 2024
A Call to Action for Generative AI in 2024
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?A Year of the Servo Reboot: Where Are We Now?
A Year of the Servo Reboot: Where Are We Now?
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptxFactors to Consider When Choosing Accounts Payable Services Providers.pptx
Factors to Consider When Choosing Accounts Payable Services Providers.pptx
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men08448380779 Call Girls In Greater Kailash - I Women Seeking Men
08448380779 Call Girls In Greater Kailash - I Women Seeking Men
 

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!!