kotlin-style-guide icon indicating copy to clipboard operation
kotlin-style-guide copied to clipboard

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

Open MyDogTom opened this issue 7 years ago • 8 comments
trafficstars

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 avatar Nov 23 '17 08:11 MyDogTom

Variant 1

val field = someFunction(
    valueA,
    valueB
) as SpecificType

class ClassA(
    paramA: String
    paramB: String
) : ClassB()

MyDogTom avatar Nov 23 '17 08:11 MyDogTom

Variant 2

val field = someFunction(
    valueA,
    valueB) as SpecificType

class ClassA(
    paramA: String
    paramB: String) : ClassB()

MyDogTom avatar Nov 23 '17 08:11 MyDogTom

Variant 3

val field = someFunction(valueA, valueB) as
      SpecificType

class ClassA(paramA: String, paramB: String) :
      ClassB()

MyDogTom avatar Nov 23 '17 08:11 MyDogTom

Variant 4

val field = someFunction(valueA, valueB)
      as SpecificType

class ClassA(paramA: String, paramB: String) 
      : ClassB()

MyDogTom avatar Nov 23 '17 08:11 MyDogTom

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 avatar Nov 23 '17 09:11 roschlau

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.

roschlau avatar Nov 23 '17 09:11 roschlau

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

yole avatar Dec 21 '17 18:12 yole

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

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

MyDogTom avatar Dec 22 '17 12:12 MyDogTom