Declaration Filtering
Query and filter declarations using Konsist API
Last updated
Query and filter declarations using Konsist API
Last updated
Declaration querying allows to 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 has performed 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 (KoClass
), properties (KoProperty
), functions (KoFunction
), 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:
Method | Description |
| returns all files present in the scope |
| returns all packages present in the scope |
| returns all imports present in the scope |
| returns all classes present in the scope |
| returns all interfaces present in the scope |
| returns all objects present in the scope |
| returns all functions present in the scope |
| returns all properties present in the scope |
| returns all type aliases present in the scope |
| 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:
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<KoClass>
: Here filter return classes annotated with UseCase
annotation:
Konsist provides a set of with...
extensions to simplify the filtering syntax. The above snippet can be improved:
The.
withAllAnnotationsOf
(Annotation1::class, Annotation2::class)
filter classes having all annotations present (Annotation1
and Annotation2
).
The.
withSomeAnnotationsOf
(Annotation1::class, Annotation2::class)
filter classes having at least one annotation (Annotation1
or Annotation2
).
Multiple conditions can be chained to perform more specific filtering. The below snippet filters classes with the BaseUseCase
parent class that resides 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:
Querying and filtering stages can be mixed to perform more specific checks. The below snippet filters classes reside in the controller
package retrieves all properties, and filters properties with Inject
annotation:
To print all declarations within use the print()
method: