Avoid comments directly within Kotlin type parameters

This product is not supported for your selected Datadog site. ().

Metadata

ID: kotlin-code-style/type-parameter-comment

Language: Kotlin

Severity: Notice

Category: Code Style

Description

In Kotlin, placing comments directly inside the angle brackets (<...>) of a type parameter declaration, such as Foo<in /* some comment */ Bar>, is considered poor code style. While this syntax is technically valid, it can significantly hinder code readability and disrupt consistent formatting, making it difficult for developers to quickly grasp the type’s definition and its intent. This practice also deviates from standard conventions where type parameters are typically kept clean, containing only essential elements like variance modifiers and the type identifier.

How to remediate

To ensure clearer and more maintainable code, move comments associated with type parameters outside the angle brackets. Comments can be placed on a separate line immediately before or after the type parameter definition, or within the containing declaration if they describe the type parameter’s overall purpose. This approach maintains code readability and adheres to common Kotlin style guidelines, making the code easier to parse and understand for other developers.

Non-Compliant Code Examples

class Foo1<in /* some comment */ Bar>

Compliant Code Examples

class Foo1<
    /* some comment */ 
    out Bar
    >
class Foo2<
    // some comment 
    out Bar
    >
https://static.datadoghq.com/static/images/logos/github_avatar.svg https://static.datadoghq.com/static/images/logos/vscode_avatar.svg jetbrains

Seamless integrations. Try Datadog Code Security