Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Sign up for free
Menu
Search
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Features
All features
Private URLs
Password Protection
Custom URLS
Scheduled publishing
Remove Branding
Restrict embedding
Deck Collections
Notes
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Explore
Featured decks
Featured speakers
Programming
Technology
Storyboards
Pricing
Search
Sign in
Sign up for free
一歩進んだ拡張関数の活用とその濫用で後悔した話 #m3kt
Search
Sponsored
·
Your Podcast. Everywhere. Effortlessly.
Share. Educate. Inspire. Entertain. You do you. We'll handle the rest.
→
Taro Nagasawa
August 25, 2017
Programming
7.4k
1
Share
Embed
Copy iframe code
Copy JS code
Copy link
Start on current slide
一歩進んだ拡張関数の活用とその濫用で後悔した話 #m3kt
どこでもKotlin #1 (
https://m3-engineer.connpass.com/event/63057/)で使用したスライドです
。
Taro Nagasawa
August 25, 2017
More Decks by Taro Nagasawa
See All by Taro Nagasawa
Android開発者のための Kotlin Multiplatform入門
ntaro
0
1.8k
Kotlin 最新動向2022 #tfcon #techfeed
ntaro
1
2.4k
#Ubie 狂気の認知施策と選考設計
ntaro
14
14k
UbieにおけるサーバサイドKotlin活用事例
ntaro
1
1.2k
KotlinでSpring 完全理解ガイド #jsug
ntaro
6
3.7k
Kotlinでサーバサイドを始めよう!
ntaro
1
1.1k
Androidからサーバーサイドまで!プログラミング言語 Kotlinの魅力 #devboost
ntaro
5
3.1k
Kotlin Contracts #m3kt
ntaro
4
4.4k
How_to_Test_Server-side_Kotlin.pdf
ntaro
1
590
Other Decks in Programming
See All in Programming
The Good Stuff, Not the Slop: Engineering High-Quality Android Apps with Modern AI Tooling
danybony
1
240
数年滞っていたダークモード対応をおよそ2週間で完了させる
chigichan24
0
700
Go × SIMDで高速化するベクトル検索 ~ルーフラインモデルでSIMDが効く境界を探れ! ~
po3rin
1
230
Family mrubyの進捗
kishima
1
110
DroidKaigi 2026 「個人開発という実験場: Android エンジニアが手にする4つの自由」
slashnephy
0
230
業務時間外もAIに働いてもらう話
colorful12
3
10k
Laravelのアプリケーションをどこにデプロイするか #ツナギメオフライン.9
akase244
0
120
thread_parallel_with_free-threaded_Python_and_NumPy.pdf
riku_sakamoto
0
290
Intent as Code
shoppingjaws
6
880
kubernetes コンポーネント開発入門 / 新卒N年目の勉強会&交流会!〜〇〇への誘い〜 #n_study
mazrean
0
200
20260914 AIエージェント時代のPlatform Engineering LLM基盤とプロダクトの責務境界線
kanfab1
3
1k
アクセシビリティから考える情報設計
high_g_engineer
0
350
Featured
See All Featured
Test your architecture with Archunit
thirion
2
2.4k
DevOps and Value Stream Thinking: Enabling flow, efficiency and business value
helenjbeal
1
380
[Rails World 2023 - Day 1 Closing Keynote] - The Magic of Rails
eileencodes
38
3k
How Software Deployment tools have changed in the past 20 years
geshan
1
34k
How to train your dragon (web standard)
notwaldorf
97
6.8k
VelocityConf: Rendering Performance Case Studies
addyosmani
331
25k
Making the Leap to Tech Lead
cromwellryan
135
10k
Art, The Web, and Tiny UX
lynnandtonic
304
22k
Introduction to Domain-Driven Design and Collaborative software design
baasie
1
980
Designing Powerful Visuals for Engaging Learning
tmiket
1
540
GraphQLの誤解/rethinking-graphql
sonatard
75
12k
Breaking role norms: Why Content Design is so much more than writing copy - Taylor Woolridge
uxyall
1
400
Transcript
一歩進んだ拡張関数の活用 とその濫用で後悔した話 どこでもKotlin #1 2017-08-24 長澤太郎 @ngsw_taro
自己紹介 • 長澤 太郎(たろーって呼んでね) • @ngsw_taro • エムスリー株式会社 • やすべえとディズニーが大好き!
宣伝 9/29発売! 好評発売中 無料で配布中 goo.gl/5vUT7o 鋭意執筆中! Kotlin in Action
もくじ 1. エクステンションからインタフェースへ 2. partial class的なやつ 3. Double Context Extension
1. エクステンションから インタフェースへ
AndroidではContextを第1引数によく取る class MyView: FrameLayout { // 各コンストラクタは省略 init { //
LayoutInflaterオブジェクトが欲しい LayoutInflater.from(context) .inflate(R.layout.my_view, this) } }
class MyView: FrameLayout { // 各コンストラクタは省略 init { // LayoutInflaterオブジェクトが欲しい
LayoutInflater.from(context) .inflate(R.layout.my_view, this) } } AndroidではContextを第1引数によく取る getContext()でも同じ
そんなときはエクステンション class MyView: FrameLayout { init { // LayoutInflaterオブジェクトが欲しい context.layoutInflater()
.inflate(R.layout.my_view, this) } } fun Context.layoutInflater(): LayoutInflater = LayoutInflater.from(this)
さらに短く class MyView: FrameLayout { init { // LayoutInflaterオブジェクトが欲しい layoutInflater()
.inflate(R.layout.my_view, this) } } fun View.layoutInflater(): LayoutInflater = LayoutInflater.from(context)
さらに短く class MyView: FrameLayout { init { // LayoutInflaterオブジェクトが欲しい layoutInflater()
.inflate(R.layout.my_view, this) } } fun View.layoutInflater(): LayoutInflater = LayoutInflater.from(context) Viewでしか使えない
似ているエクステンションを量産? class MyAdapter: ArrayAdapter<MyItem> { override fun getView(...) { //
LayoutInflaterオブジェクトが欲しい layoutInflater() .inflate(R.layout.item_view, null) } } fun ArrayAdapter<*>.layoutInflater(): LayoutInflater = LayoutInflater.from(context)
インタフェースで共通部分を抽出 interface ContextHolder { fun getContext(): Context } fun ContextHolder.layoutInflater():
LayoutInflater = LayoutInflater.from(getContext())
ContextHolderと拡張関数1個で賄える class MyAdapter: ArrayAdapter<MyItem>, ContextHolder { override fun getView(...) {
layoutInflater().inflate(...) } } class MyView: FrameLayout, ContextHolder { init { layoutInflater().inflate(...) }
2. partial class的なやつ
大きくなりがちなActivity class MainActivity: AppCompatActivity() { var textView: TextView? = null
override fun onCreate(bundle: Bundle?) { super.onCreate(bundle) prepare() setupViews() } private fun prepare() {...} private fun setupViews() {...} }
大きくなりがちなActivity class MainActivity: AppCompatActivity() { var textView: TextView? = null
override fun onCreate(bundle: Bundle?) { super.onCreate(bundle) prepare() setupViews() } private fun prepare() {...} private fun setupViews() {...} } privateなヘルパーメソッド
インタフェース+エクステンションで分割 class MainActivity: AppCompatActivity(), MainActivityHelper { override fun onCreate(bundle: Bundle?)
{ super.onCreate(bundle) prepare() setupViews() } interface MainActivityHelper { fun MainActivity.prepare() {...} fun MainActivity.setupViews() {...} }
インタフェース+エクステンションで分割 class MainActivity: AppCompatActivity(), MainActivityHelper { override fun onCreate(bundle: Bundle?)
{ super.onCreate(bundle) prepare() setupViews() } interface MainActivityHelper { fun MainActivity.prepare() {...} fun MainActivity.setupViews() {...} } ヘルパーメソッドを 拡張関数として定義
公開されているレシーバのAPIが使える interface MainActivityHelper { fun MainAcitivty.prepare() { ... } fun
MainActivity.setupViews() { setContentView(R.layout.activity_main) textView = findViewById(R.id.text_view) } }
3. Double Context Extension
こんな関数呼び出しをしたい! class MyActivity: AppCompatActivity() { ... fun showMessage() { //
myDialog.show(supportFragmentManager, "tag") myDialog.show("tag") } }
class MyActivity: AppCompatActivity() { ... fun showMessage() { // myDialog.show(supportFragmentManager,
"tag") myDialog.show("tag") } } こんな関数呼び出しをしたい! これを渡すのはお決まりだから 省略したい
class MyActivity: AppCompatActivity() { ... fun showMessage() { // myDialog.show(supportFragmentManager,
"tag") myDialog.show("tag") } } こんな関数呼び出しをしたい! DialogFragmentに拡張関数showを生やせば? いや、プロパティsupportFragmentManagerが必要だ... →FragmentManagerに依存
方法1: エクステンション in インタフェース interface DialogFeature { fun getSupportFragmentManager(): FragmentManager
fun DialogFragment.show(tag: String) { show(getSupportFragmentManager(), tag) } } class MyActivity: AppComatActivity(), DialogFeature { ... fun showMessage() { myDialog.show("tag) }
方法1: エクステンション in インタフェース interface DialogFeature { fun getSupportFragmentManager(): FragmentManager
fun DialogFragment.show(tag: String) { show(getSupportFragmentManager(), tag) } } class MyActivity: AppComatActivity(), DialogFeature { ... fun showMessage() { myDialog.show("tag) } インタフェースを 実装したくない!
方法2: Double Context Extension • 2つのコンテキストを持った拡張関数 • 命名 by 私
• 見た目: 型Aの定義中で、型Aに依存しながらも型Bの拡張関 数を生やすことができる class MyActivity: AppCompatActivity() { ... fun showMessage() { myDialog.show("tag") } } この関数は、引数の他に DialogFragmentとFragmentActivity の2つに依存する
タネ明かし • 実際のコード: 「B型の拡張関数」を返す「A型の拡張プロパ ティ」を定義する // 別の適当なファイル val FragmentActivity.show: DialogFragment.(String)->Unit
get() = { tag -> show(supportFragmentManager, tag) }
どう解釈されるのか val FragmentActivity.show: DialogFragment.(String)->Unit get() = { tag -> show(supportFragmentManager,
tag) } class MyActivity: AppCompatActivity() { ... fun showMessage() { myDialog.show("tag") } }
どう解釈されるのか val FragmentActivity.show: DialogFragment.(String)->Unit get() = { tag -> show(supportFragmentManager,
tag) } class MyActivity: AppCompatActivity() { ... fun showMessage() { myDialog.show("tag") } }
どう解釈されるのか val FragmentActivity.show: DialogFragment.(String)->Unit get() = { tag -> show(supportFragmentManager,
tag) } class MyActivity: AppCompatActivity() { ... fun showMessage() { myDialog.show("tag") } } myDialog.(this.show)("tag") と書いても同じ
どう解釈されるのか val FragmentActivity.show: DialogFragment.(String)->Unit get() = { tag -> show(supportFragmentManager,
tag) } class MyActivity: AppCompatActivity() { ... fun showMessage() { myDialog.show("tag") } }
どう解釈されるのか val FragmentActivity.show: DialogFragment.(String)->Unit get() = { tag -> show(supportFragmentManager,
tag) } class MyActivity: AppCompatActivity() { ... fun showMessage() { myDialog.show("tag") } }
どう解釈されるのか val FragmentActivity.show: DialogFragment.(String)->Unit get() = { tag -> show(supportFragmentManager,
tag) } class MyActivity: AppCompatActivity() { ... fun showMessage() { myDialog.show("tag") } }
どう解釈されるのか val FragmentActivity.show: DialogFragment.(String)->Unit get() = { tag -> show(supportFragmentManager,
tag) } class MyActivity: AppCompatActivity() { ... fun showMessage() { myDialog.show("tag") } }
どう解釈されるのか val FragmentActivity.show: DialogFragment.(String)->Unit get() = { tag -> show(supportFragmentManager,
tag) } class MyActivity: AppCompatActivity() { ... fun showMessage() { myDialog.show("tag") } } A.(B)->Cは(A, B)->Cと 見なせる性質を利用して show(myDialog, "tag") or show.invoke(myDialog, "tag")
すごく ない?
いや、 わけわか らん
まとめ • 拡張関数って便利だよね • でも限界がある • インタフェースと組み合わせる • Double Context
Extensionという提案
まとめ • 拡張関数って便利だよね • でも限界がある • インタフェースと組み合わせる • Double Context
Extensionという提案 • 変なことしないで素直なコードを心がけましょう
エムスリーで 僕とKotlin