SlideShare a Scribd company logo
1 of 15
Download to read offline
Kotlin在Android中的應⽤用
Cast, Better Callback, Extension functions
Lutas Lin
2019.05.03
Taiwan Kotlin User Group - Kotlin Book Club 2019
Sample Code連結
https://github.com/lutas2000/Android-Kotlin-Sample
Cast
• 什什麼是Cast?
Main Activity
MainFragment KotlinFragmentJavaFragment
PM : 老闆希望紀錄User離開App時的⾴頁⾯面
Main Activity
MainFragment KotlinFragmentJavaFragment
Reportable
report()
private Fragment currentFragment;
@Override
protected void onDestroy() {
super.onDestroy();
((Reportable)currentFragment).report();
}
public interface Reportable {
public void report();
}
Reportable.java
MainActivity.java
Main Activity
MainFragment KotlinFragmentJavaFragment
Reportable
report()
PM : 對了了,MainFragment別回報!
Caused by: java.lang.ClassCastException:
lutas.sample.kotlinandroid.MainFragment cannot be cast to
lutas.sample.kotlinandroid.Reportable
糟糕!
MainActivity.java
@Override
protected void onDestroy() {
super.onDestroy();
if (currentFragment instanceof Reportable) {
((Reportable) currentFragment).report();
}
}
Kotlin有更更好的寫法嗎?
Safe Cast
(currentFragment as? Reportable)?.report()
Type Check and Smart Cast
if (currentFragment is Reportable) {
currentFragment.report()
}
Callback
• 如何寫⼀一個Callback ?
class A {
interface Callback {
public void onDone();
}
private void action(Callback callback) {
// Do something
callback.onDone();
}
}
A a = new A();
a.action(new Callback() {
@Override
public void onDone() {
// Do something
}
});
Kotlin有更更好的寫法嗎?
class A {
fun action(onDone: () -> Unit) {
// Do something
onDone()
}
}
val a = A()
a.action {
// Do something
}
Lambda as Parameters
Extension Functions
• EditText的TextWatcher Interface好煩!

• 要override三個function: beforeTextChanged,
onTextChanged, afterTextChanged

• afterTextChanged的parameter還不是String!
EditTextUtil.java
interface OnChangedListener {
public void onChanged(String text);
}
public static void setOnTextChangedListener(
EditText editText,
final OnChangedListener listener
) {
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(…) {
}
@Override
public void onTextChanged(…) {
}
@Override
public void afterTextChanged(Editable s) {
listener.onChanged(s.toString());
}
});
}
EditTextUtil.java
EditTextUtil.setOnTextChangedListener(editText,
new EditTextUtil.OnChangedListener() {
@Override
public void onChanged(String text) {
Log.d(TAG, "text changed: "+ text);
}
}
);
EditTextExt.kt
fun EditText.setOnTextChangedListener(onChanged: (String) -> Unit) {
addTextChangedListener(object: TextWatcher {
override fun afterTextChanged(s: Editable) {
onChanged(s.toString())
}
override fun beforeTextChanged(…) {
}
override fun onTextChanged(…) {
}
})
}
editText.setOnTextChangedListener {
Log.d(TAG, "text changed: $it")
}
使⽤用情境

More Related Content

Similar to Kotlin在android中的應用

Dropwizard and Friends
Dropwizard and FriendsDropwizard and Friends
Dropwizard and FriendsYun Zhi Lin
 
How to code to code less
How to code to code lessHow to code to code less
How to code to code lessAnton Novikau
 
RIBs - Fragments which work
RIBs - Fragments which workRIBs - Fragments which work
RIBs - Fragments which workDmitry Zaytsev
 
Tb Ly And Html5
Tb Ly And Html5Tb Ly And Html5
Tb Ly And Html5taobao.com
 
Spring Boot with Kotlin, Kofu and Coroutines
 Spring Boot with Kotlin, Kofu and Coroutines Spring Boot with Kotlin, Kofu and Coroutines
Spring Boot with Kotlin, Kofu and CoroutinesVMware Tanzu
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVMSylvain Wallez
 
Bootiful Reactive Testing with Mario Gray
Bootiful Reactive Testing with Mario GrayBootiful Reactive Testing with Mario Gray
Bootiful Reactive Testing with Mario GrayVMware Tanzu
 
Potato04 The end of confusion of callback between activity and fragment.
Potato04 The end of confusion of callback between activity and fragment.Potato04 The end of confusion of callback between activity and fragment.
Potato04 The end of confusion of callback between activity and fragment.Toshihiro Yagi
 
Getting Started With Kotlin
Getting Started With KotlinGetting Started With Kotlin
Getting Started With KotlinGaurav sharma
 
Framework Engineering Revisited
Framework Engineering RevisitedFramework Engineering Revisited
Framework Engineering RevisitedYoungSu Son
 
Knowledge sharing session Java 9
Knowledge sharing session Java 9Knowledge sharing session Java 9
Knowledge sharing session Java 9Thomas Engels
 
What's Expected in Java 7
What's Expected in Java 7What's Expected in Java 7
What's Expected in Java 7Gal Marder
 
Kotlin – Alternative oder Ergänzung zu Java?
Kotlin – Alternative oder Ergänzung zu Java?Kotlin – Alternative oder Ergänzung zu Java?
Kotlin – Alternative oder Ergänzung zu Java?gedoplan
 
Microservices Architecture: Labs
Microservices Architecture: LabsMicroservices Architecture: Labs
Microservices Architecture: Labsgjuljo
 
Grails 4: Upgrade your Game!
Grails 4: Upgrade your Game!Grails 4: Upgrade your Game!
Grails 4: Upgrade your Game!Zachary Klein
 
The Journey of Craftmanship – Kotlin in Action
The Journey of Craftmanship – Kotlin in ActionThe Journey of Craftmanship – Kotlin in Action
The Journey of Craftmanship – Kotlin in Actionraditya gumay
 
GOTO - The Ultimate Android Lock Screen
GOTO - The Ultimate Android Lock ScreenGOTO - The Ultimate Android Lock Screen
GOTO - The Ultimate Android Lock ScreenInnoWeb Tech, LLC
 

Similar to Kotlin在android中的應用 (20)

Dropwizard and Friends
Dropwizard and FriendsDropwizard and Friends
Dropwizard and Friends
 
How to code to code less
How to code to code lessHow to code to code less
How to code to code less
 
PWA with Kotlin
PWA with KotlinPWA with Kotlin
PWA with Kotlin
 
RIBs - Fragments which work
RIBs - Fragments which workRIBs - Fragments which work
RIBs - Fragments which work
 
Tb Ly And Html5
Tb Ly And Html5Tb Ly And Html5
Tb Ly And Html5
 
Spring Boot with Kotlin, Kofu and Coroutines
 Spring Boot with Kotlin, Kofu and Coroutines Spring Boot with Kotlin, Kofu and Coroutines
Spring Boot with Kotlin, Kofu and Coroutines
 
Native Java with GraalVM
Native Java with GraalVMNative Java with GraalVM
Native Java with GraalVM
 
Bootiful Reactive Testing with Mario Gray
Bootiful Reactive Testing with Mario GrayBootiful Reactive Testing with Mario Gray
Bootiful Reactive Testing with Mario Gray
 
Potato04 The end of confusion of callback between activity and fragment.
Potato04 The end of confusion of callback between activity and fragment.Potato04 The end of confusion of callback between activity and fragment.
Potato04 The end of confusion of callback between activity and fragment.
 
Getting Started With Kotlin
Getting Started With KotlinGetting Started With Kotlin
Getting Started With Kotlin
 
Framework Engineering Revisited
Framework Engineering RevisitedFramework Engineering Revisited
Framework Engineering Revisited
 
Knowledge sharing session Java 9
Knowledge sharing session Java 9Knowledge sharing session Java 9
Knowledge sharing session Java 9
 
What's Expected in Java 7
What's Expected in Java 7What's Expected in Java 7
What's Expected in Java 7
 
Kotlin – Alternative oder Ergänzung zu Java?
Kotlin – Alternative oder Ergänzung zu Java?Kotlin – Alternative oder Ergänzung zu Java?
Kotlin – Alternative oder Ergänzung zu Java?
 
Microservices Architecture: Labs
Microservices Architecture: LabsMicroservices Architecture: Labs
Microservices Architecture: Labs
 
Grails 4: Upgrade your Game!
Grails 4: Upgrade your Game!Grails 4: Upgrade your Game!
Grails 4: Upgrade your Game!
 
The Journey of Craftmanship – Kotlin in Action
The Journey of Craftmanship – Kotlin in ActionThe Journey of Craftmanship – Kotlin in Action
The Journey of Craftmanship – Kotlin in Action
 
從零開始學 Android
從零開始學 Android從零開始學 Android
從零開始學 Android
 
GOTO - The Ultimate Android Lock Screen
GOTO - The Ultimate Android Lock ScreenGOTO - The Ultimate Android Lock Screen
GOTO - The Ultimate Android Lock Screen
 
Spring Boot
Spring BootSpring Boot
Spring Boot
 

Recently uploaded

UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewDianaGray10
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform EngineeringMarcus Vechiato
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxjbellis
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxMarkSteadman7
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentationyogeshlabana357357
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxFIDO Alliance
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!Memoori
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightSafe Software
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMKumar Satyam
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfdanishmna97
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxFIDO Alliance
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfalexjohnson7307
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontologyjohnbeverley2021
 
الأمن السيبراني - ما لا يسع للمستخدم جهله
الأمن السيبراني - ما لا يسع للمستخدم جهلهالأمن السيبراني - ما لا يسع للمستخدم جهله
الأمن السيبراني - ما لا يسع للمستخدم جهلهMohamed Sweelam
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuidePixlogix Infotech
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctBrainSell Technologies
 
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdfFrisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdfAnubhavMangla3
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...panagenda
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe中 央社
 

Recently uploaded (20)

UiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overviewUiPath manufacturing technology benefits and AI overview
UiPath manufacturing technology benefits and AI overview
 
Working together SRE & Platform Engineering
Working together SRE & Platform EngineeringWorking together SRE & Platform Engineering
Working together SRE & Platform Engineering
 
Vector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptxVector Search @ sw2con for slideshare.pptx
Vector Search @ sw2con for slideshare.pptx
 
Simplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptxSimplifying Mobile A11y Presentation.pptx
Simplifying Mobile A11y Presentation.pptx
 
AI mind or machine power point presentation
AI mind or machine power point presentationAI mind or machine power point presentation
AI mind or machine power point presentation
 
Design Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptxDesign Guidelines for Passkeys 2024.pptx
Design Guidelines for Passkeys 2024.pptx
 
State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!State of the Smart Building Startup Landscape 2024!
State of the Smart Building Startup Landscape 2024!
 
The Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and InsightThe Zero-ETL Approach: Enhancing Data Agility and Insight
The Zero-ETL Approach: Enhancing Data Agility and Insight
 
Introduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDMIntroduction to use of FHIR Documents in ABDM
Introduction to use of FHIR Documents in ABDM
 
How to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cfHow to Check CNIC Information Online with Pakdata cf
How to Check CNIC Information Online with Pakdata cf
 
ADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptxADP Passwordless Journey Case Study.pptx
ADP Passwordless Journey Case Study.pptx
 
Generative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdfGenerative AI Use Cases and Applications.pdf
Generative AI Use Cases and Applications.pdf
 
Six Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal OntologySix Myths about Ontologies: The Basics of Formal Ontology
Six Myths about Ontologies: The Basics of Formal Ontology
 
الأمن السيبراني - ما لا يسع للمستخدم جهله
الأمن السيبراني - ما لا يسع للمستخدم جهلهالأمن السيبراني - ما لا يسع للمستخدم جهله
الأمن السيبراني - ما لا يسع للمستخدم جهله
 
JavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate GuideJavaScript Usage Statistics 2024 - The Ultimate Guide
JavaScript Usage Statistics 2024 - The Ultimate Guide
 
Overview of Hyperledger Foundation
Overview of Hyperledger FoundationOverview of Hyperledger Foundation
Overview of Hyperledger Foundation
 
ERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage IntacctERP Contender Series: Acumatica vs. Sage Intacct
ERP Contender Series: Acumatica vs. Sage Intacct
 
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdfFrisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
Frisco Automating Purchase Orders with MuleSoft IDP- May 10th, 2024.pptx.pdf
 
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
Easier, Faster, and More Powerful – Alles Neu macht der Mai -Wir durchleuchte...
 
Portal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russePortal Kombat : extension du réseau de propagande russe
Portal Kombat : extension du réseau de propagande russe
 

Kotlin在android中的應用