Skip to content

Kotlin

This page curates a list of example ast-grep rules to check and to rewrite Kotlin code.

Ensure Clean Architecture

Description

This ast-grep rule ensures that the domain package in a Clean Architecture project does not import classes from the data or presentation packages. It enforces the separation of concerns by preventing the domain layer from depending on other layers, maintaining the integrity of the architecture.

For example, the rule will trigger an error if an import statement like import com.example.data.SomeClass or import com.example.presentation.AnotherClass is found within the domain package.

The rule uses the files field to apply only to the domain package.

YAML

yaml
id: import-dependency-violation
message: Import Dependency Violation
notes: Ensures that imports comply with architectural rules.
severity: error
rule:
  pattern: import $PATH  # capture the import statement
constraints:
  PATH: # find specific package imports
    any:
    - regex: com\.example(\.\w+)*\.data
    - regex: com\.example(\.\w+)*\.presentation
files:  # apply only to domain package
- com/example/domain/**/*.kt

Example

kotlin
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelScope
import com.example.customlintexample.data.models.UserDto
import com.example.customlintexample.domain.usecases.GetUserUseCase
import com.example.customlintexample.presentation.states.MainState
import dagger.hilt.android.lifecycle.HiltViewModel

Contributed by

Inspired by the post Custom Lint Task Configuration in Gradle with Kotlin DSL

Made with ❤️ with Rust