kotlinpoet icon indicating copy to clipboard operation
kotlinpoet copied to clipboard

Allow generating where clauses for complex type constraints

Open metarag opened this issue 2 years ago • 4 comments

Is your feature request related to a problem? Please describe. Kotlin supports where clauses which can make complex type-constraints more readable. For example,

class GenericPerson<Self, Builder> where
Self : GenericPerson<Self, Builder>,
Builder: GenericPersonBuilder<Builder, Self>

class GenericPersonBuilder<Self, Built> where
Self : GenericPersonBuilder<Self, Built>,
Built : GenericPerson<Built, Self>

Describe the solution you'd like It would be nice if KotlinPoet allowed generating APIs like that. I'm not sure what the best way to go about this is.

Perhaps, TypeSpec.classBuilder("...").useWhereClauseForTypeConstraints(true).build()?

Describe alternatives you've considered I'm just using the existing APIs to declare the type constraints inline for now.

Additional context N/A

metarag avatar Mar 14 '23 00:03 metarag

In general we are opposed to functionality which lets the user change the formatting of the output. I would be much more supportive of a simple rule that applies globally. We do similar things for when to wrap function parameters onto multiple lines, for example.

JakeWharton avatar Mar 14 '23 00:03 JakeWharton

Fair enough. How about a rule like this?

Use the where clause if the type variables + bounds take up more than 80 chars && there’s at least a 50% reduction in length for the type variables declaration when the bounds are removed.

metarag avatar Mar 14 '23 16:03 metarag

I was thinking:

  • Has any type parameters with more than one bound, or
  • Has two+ type parameters any of which has a bound

JakeWharton avatar Mar 14 '23 18:03 JakeWharton

Yep. That looks better :)

metarag avatar Mar 14 '23 22:03 metarag