pinterest / ktlint

An anti-bikeshedding Kotlin linter with built-in formatter
https://pinterest.github.io/ktlint/
MIT License
6.18k stars 505 forks source link

Add "First method line is empty" check #440

Closed igorwojda closed 5 years ago

igorwojda commented 5 years ago

OK

fun bar() {
   val a = 2
}

Fail

fun bar() {

   val a = 2
}
igorwojda commented 5 years ago

Probably we should also add an equiwalent check for last empty method line

OK

fun bar() {
   val a = 2
}

Fail

fun bar() {
   val a = 2

}
sowmyav24 commented 5 years ago

The last empty method line check should be covered by the rule NoBlankLineBeforeRbraceRule.

sowmyav24 commented 5 years ago

Created a PR for first method line empty rule. In addition to the scenarios present above, few others that would be covered are

fun bar() {
   if(someCondition) {

    val a = 2
   }
}
shashachu commented 5 years ago

Fixed in https://github.com/pinterest/ktlint/pull/474

Zayankovsky commented 5 years ago

This method triggers no-empty-first-line-in-method-block error:

fun whatever() {
    window.addMouseListener(object : MouseAdapter() {

        override fun mouseClicked(e: MouseEvent) { /*...*/ }

        override fun mouseEntered(e: MouseEvent) { /*...*/ }
    })
}

Should it be this way? I prefer to keep first line in complex object expressions empty, just like in classes.

sowmyav24 commented 5 years ago

https://github.com/pinterest/ktlint/pull/461#issue-286397143

In addition to checking for first line blank in a method block, it will check for any first blank line in code blocks of the method.Please let me know if the subsequent code blocks in the method need to be ignored from this check.

Since, the object expression is inside the method, it triggers a violation for the same.

Zayankovsky commented 4 years ago

Both Kotlin Coding Conventions and Android Kotlin style guide don't mention anything about such a requirement. Why is it forced then? I believe object expressions should be excluded from this check.

JakeWharton commented 4 years ago

Actually the Android Kotlin style guide explicitly mentions this whitespace:

Optionally before the first statement in a function, before the first member of a class, or after the last member of a class (neither encouraged nor discouraged).

Zayankovsky commented 4 years ago

Sorry for not making it clear in the first place, I was talking specifically about object expressions inside methods.

JakeWharton commented 4 years ago

That is an anonymous definition of a class which has the same rules as any other class declaration. If that's not clear, we can amend the guide to explicitly denote that syntactical construct as being synonymous with a class definition.