LoginSignup
4
6

More than 5 years have passed since last update.

ktlintに入門してみた(LT会資料)

Posted at
1 / 11

ktlint?

05311367c073c20fba1801b528655d74.png

・Kotlinの静的コード解析(Linter)
 https://ktlint.github.io/

コードのフォーマットをいい感じに整えてくれるやつ


例: 1

if (condition){
 // do something
}

:relaxed:

if (condition) {
 // do something
}

例: 2

val count = 10
Log.d("count", "count: ${count}")

:blush:

val count = 10
Log.d("count", "count: $count")

Standard rules

EditorConfig
→独自の設定も可能!
https://github.com/shyiko/ktlint#editorconfig


導入方法

app/build.gradle
+ configurations {
+    ktlint
+ }

+ dependencies {
+   ktlint "com.github.shyiko:ktlint:0.20.0"
+ }

+ task ktlint(type: JavaExec, group: "verification") {
+    description = "Check Kotlin code style."
+    classpath = configurations.ktlint
+    main = "com.github.shyiko.ktlint.Main"
+    args "src/**/*.kt"
+    // to generate report in checkstyle format prepend following args:
+    // "--reporter=plain", "--reporter=checkstyle,output=${buildDir}/ktlint.xml"
+    // see https://github.com/shyiko/ktlint#usage for more
+ }

+ check.dependsOn ktlint

+ task ktlintFormat(type: JavaExec, group: "formatting") {
+    description = "Fix Kotlin code style deviations."
+    classpath = configurations.ktlint
+    main = "com.github.shyiko.ktlint.Main"
+    args "-F", "src/**/*.kt"
+ }

参考 : https://github.com/shyiko/ktlint#-with-gradle


導入後

./gradlew ktlint
→ スタイルのチェック

./gradlew ktlintFormat
→ スタイルをフォーマット


ビルド時にフォーマットが走るように

app/build.gradle
android {
  ...

 applicationVariants.all {
    ktlintFormat.execute()
  }

  ...
}

※デバッグビルド時だけ実行するようにしたほうがいいかもしれない。


DEMO

3626451a73e26a9e3455daeafa4d7d86.png

↓ ビルド実行後

e50d57c27e0455c0ee9c68e4e72f446f.png


まとめ

  • フォーマットが整うとレビューなども楽になって、捗るかもしれない :relaxed:
  • Dangerと組み合わせられるといいかもしれない :rocket:

  • Android Studioのコードフォーマットとあまり違いがわからなかった :sweat_smile:


参考資料 :bow:

4
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
6