Declaration Filtering
Query and filter declarations using Konsist API
Query Declarations
Declaration querying allows retrieval of declarations of a given type. It is the middle step of the Konsist config preceded by scope retrieval (Create The Scope) and followed by the verification (Declaration Assertion) step.
Typically, verification is performed on a collection of declarations such as methods marked with particular annotations or classes located within a single package.
Every Create The Scope contains a set of declarations (Declaration) such as classes (KoClassDeclaration), properties (KoPropertyDeclaration), functions (KoFunctionDeclaration), etc. The KoScope class provides a set of properties and methods to access Kotlin declarations. Each of them returns a list representing a declaration subset:
files
returns all files present in the scope
packages
returns all packages present in the scope
imports
returns all imports present in the scope
annotations
returns all file annotations (e.g. @file:Suppress) present in the scope
classes()
returns all classes present in the scope
interfaces()
returns all interfaces present in the scope
objects()
returns all objects present in the scope
companionObjects()
returns all companion objects present in the scope
functions()
returns all functions present in the scope
properties()
returns all properties present in the scope
typeAliases
returns all type aliases present in the scope
declarations()
returns all declarations present in the scope
To get all classes from the given scope use KoScope.classes() method:
Here is an example of querying all properties defined inside classes:
Filter Declarations
More granular filtering can be applied to additionally filter classes annotated with certain attributes like classes annotated with UseCase annotation.
Konsist is compatible with Kotlin Collection processing API, so the filter method can be used to filter the content of the List<KoClassDeclaration>. Here, filter returns classes annotated with UseCase annotation:
Konsist provides a set of with... extensions to simplify the filtering syntax. The above snippet can be improved:
Multiple conditions can be chained to perform more specific filtering. The below snippet filters classes annotated with the UseCase annotation that reside in the usecase package:
It is also possible to filter declarations by using certain aspects e.g. visibility modifiers. Usage of providers allows verifying the visibility of different declaration types such as classes, functions, properties, etc:
Query And Filter Declaration
Querying and filtering stages can be mixed to perform more specific checks. The below snippet filters classes residing in the controller package, retrieves all properties, and filters properties with the Inject annotation:
Print Declarations
To print all declarations within the list, use the print() method:
Last updated