【问题标题】:IntelliJ does not sort Kotlin imports according to ktlint's expectationsIntelliJ 不会根据 ktlint 的期望对 Kotlin 导入进行排序
【发布时间】:2020-01-21 21:42:13
【问题描述】:

当我选择代码 → 优化导入或代码 → 重新格式化代码时,IntelliJ 优化和排序导入,但即使我使用 Kotlin 代码样式中的代码样式设置,导入也不会排序按字典顺序(至少不完全)。例如,这是产生的输出:

import com.fasterxml.jackson.databind.ObjectMapper
import io.dropwizard.jackson.Jackson
import io.kotlintest.assertSoftly
import io.kotlintest.matchers.types.shouldBeNull
import io.kotlintest.shouldBe
import io.kotlintest.specs.ShouldSpec
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.intellij.lang.annotations.Language
import java.time.Instant // This should not be at the bottom!!!

虽然这是 ktlint 所期望的:

import com.fasterxml.jackson.databind.ObjectMapper
import io.dropwizard.jackson.Jackson
import io.kotlintest.assertSoftly
import io.kotlintest.matchers.types.shouldBeNull
import io.kotlintest.shouldBe
import io.kotlintest.specs.ShouldSpec
import java.time.Instant // should be here instead
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import org.intellij.lang.annotations.Language

换句话说,格式化程序似乎总是将来自java.* 包的导入放在底部,无论如何。有没有办法让它符合 ktlint 的期望(以及实际构成词典顺序的内容)?我缺少任何隐藏选项或其他什么?

我正在使用 IntelliJ IDEA 2019.3.1(终极版)和 Kotlin 插件版本 1.3.61-release-IJ2019.3-1。 ktlint 的版本是 0.36.0

【问题讨论】:

    标签: kotlin intellij-idea


    【解决方案1】:

    这是 Kotlin IDEA 插件中的一个错误/缺失功能:https://youtrack.jetbrains.com/issue/KT-10974。请投票。

    【讨论】:

    • 看起来导入布局功能是为 Kotlin 1.4 设计的,可以通过 .editorconfig[*.{kt,kts}] 之类的部分中使用 disabled_rules=import-ordering 之类的配置规则禁用该规则。
    【解决方案2】:

    您可以更改 IntelliJ 对 Kotlin 的导入顺序以满足ktlint

    Settings > Editor > Code Style > Kotlin 中,您可以通过从列表中删除除import all other imports 之外的所有内容来更改Import Layout

    之前:

    之后:

    【讨论】:

    • 感谢您的回答。显然,当我问这个问题时,IntelliJ 中并没有这样的功能。
    【解决方案3】:

    对我有用的是手动删除所有导入,然后重新导入每个导入。

    【讨论】:

    • 不是最佳实践和简单的事情,但有帮助
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多