Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
一歩進んだ拡張関数の活用とその濫用で後悔した話 #m3kt
Search
Taro Nagasawa
August 25, 2017
Programming
1
7.1k
一歩進んだ拡張関数の活用とその濫用で後悔した話 #m3kt
どこでもKotlin #1 (
https://m3-engineer.connpass.com/event/63057/)で使用したスライドです
。
Taro Nagasawa
August 25, 2017
Tweet
Share
More Decks by Taro Nagasawa
See All by Taro Nagasawa
Android開発者のための Kotlin Multiplatform入門
ntaro
0
530
Kotlin 最新動向2022 #tfcon #techfeed
ntaro
1
2.2k
#Ubie 狂気の認知施策と選考設計
ntaro
13
13k
UbieにおけるサーバサイドKotlin活用事例
ntaro
1
1.1k
KotlinでSpring 完全理解ガイド #jsug
ntaro
6
3.4k
Kotlinでサーバサイドを始めよう!
ntaro
1
950
Androidからサーバーサイドまで!プログラミング言語 Kotlinの魅力 #devboost
ntaro
5
2.6k
Kotlin Contracts #m3kt
ntaro
4
3.9k
How_to_Test_Server-side_Kotlin.pdf
ntaro
1
470
Other Decks in Programming
See All in Programming
楽しく向き合う例外対応
okutsu
0
500
CDK開発におけるコーディング規約の運用
yamanashi_ren01
2
190
さいきょうのレイヤードアーキテクチャについて考えてみた
yahiru
3
760
React 19アップデートのために必要なこと
uhyo
4
730
時計仕掛けのCompose
mkeeda
1
310
GoとPHPのインターフェイスの違い
shimabox
2
200
1年目の私に伝えたい!テストコードを怖がらなくなるためのヒント/Tips for not being afraid of test code
push_gawa
1
430
パスキーのすべて ── 導入・UX設計・実装の紹介 / 20250213 パスキー開発者の集い
kuralab
3
830
PHP ステートレス VS ステートフル 状態管理と並行性 / php-stateless-stateful
ytake
0
110
dbt Pythonモデルで実現するSnowflake活用術
trsnium
0
210
一休.com のログイン体験を支える技術 〜Web Components x Vue.js 活用事例と最適化について〜
atsumim
0
670
Django NinjaによるAPI開発の効率化とリプレースの実践
kashewnuts
1
150
Featured
See All Featured
The MySQL Ecosystem @ GitHub 2015
samlambert
250
12k
実際に使うSQLの書き方 徹底解説 / pgcon21j-tutorial
soudai
175
52k
A Tale of Four Properties
chriscoyier
158
23k
Refactoring Trust on Your Teams (GOTO; Chicago 2020)
rmw
33
2.8k
Designing Experiences People Love
moore
140
23k
GitHub's CSS Performance
jonrohan
1030
460k
Designing for humans not robots
tammielis
250
25k
Agile that works and the tools we love
rasmusluckow
328
21k
YesSQL, Process and Tooling at Scale
rocio
172
14k
Bootstrapping a Software Product
garrettdimon
PRO
306
110k
Optimising Largest Contentful Paint
csswizardry
34
3.1k
Scaling GitHub
holman
459
140k
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