Kotlin / kotlin-style-guide

Work-in-progress notes for the Kotlin style guide
288 stars 14 forks source link

How to break line when cast ("as") or colon (":") is present #45

Open MyDogTom opened 6 years ago

MyDogTom commented 6 years ago

How to to properly break line cast (as, as?) or colon (:) is present and it doesn't fit in one line? I think variants 1 and 2 are good, 3 is acceptable, 4 should be forbidden.

MyDogTom commented 6 years ago

Variant 1

val field = someFunction(
    valueA,
    valueB
) as SpecificType

class ClassA(
    paramA: String
    paramB: String
) : ClassB()
MyDogTom commented 6 years ago

Variant 2

val field = someFunction(
    valueA,
    valueB) as SpecificType

class ClassA(
    paramA: String
    paramB: String) : ClassB()
MyDogTom commented 6 years ago

Variant 3

val field = someFunction(valueA, valueB) as
      SpecificType

class ClassA(paramA: String, paramB: String) :
      ClassB()
MyDogTom commented 6 years ago

Variant 4

val field = someFunction(valueA, valueB)
      as SpecificType

class ClassA(paramA: String, paramB: String) 
      : ClassB()
roschlau commented 6 years ago

I actually prefer variants 1 and 4 over the others. My reasoning being that I see as SpecificType and : ClassB() as one single term each that shouldn't be split over two lines (thus ruling out variant 3), and should only be put on one line with another expression if the complete expression fits readably on one line as a whole (which disqualifies variant 2, which I personally find aesthetically unpleasing as well).

It comes down to readability, 3 splits coherent terms in the middle, and 2 puts them on the same line with the last part of the expression before it without any good reason to do so, while the rest of that expression is otherwise nicely chunked up, which again makes for poor readability in my opinion.

roschlau commented 6 years ago

I would discourage variant 4 for classes though, as those should always either be true one-liners or have their primary constructor paramaters on individual lines, that one-line-but-inheritance-on-another-line-approach looks weird there. So I'd say 1 or 4 for casts, whatever fits better, but only 1 for inheritance.

yole commented 6 years ago

For class header formatting, see #2. For as, could you please clarify how this is different from other operators?

MyDogTom commented 6 years ago

For as, could you please clarify how this is different from other operators

I would say no difference. Do you have recommendation for operators?