Verify Generics
Type Parameter vs Type Argument
To understand the Konsist API, let's look at the difference between generic type parameters and generic type arguments:
Type Parameter is the placeholder (like
T) you write when creating a class or function (declaration site)Type Argument is the actual type (like
StringorInt) you provide when using that class or function (use site)
Simple Examples:
// Example 1: Class
// Here 'T' is a TYPE PARAMETER
class Box<T>(val item: T)
// Here 'String' is a TYPE ARGUMENT
val stringBox = Box<String>("Hello")
// Example 2: Function
// Here 'T' is a TYPE PARAMETER
fun <T> printWithType(item: T) {
println("Type is: ${item::class.simpleName}")
}
// Here 'String' is a TYPE ARGUMENT
printWithType<String>("Hello") // prints: Type is: StringVerify Type Parameters
Type parameters can be defined, for example, inside class or function.
Check whether a class's generic type parameter has the name UiState:
Check whether class type parameters has out modifier:
Verify Type Arguments
Check whether a property generic type argument has the name Service:
The flatten() extension method allows flattening the type arguments structure:
For a type like
String, it returnslistOf().For a type like
List<String>, it returnslistOf(String).For a type like
Map<List<String>, Int>, it returnslistOf(List, String, Int).
Check if all function parameters have generic type argument ending with UIState:
Check all parents have String type argument:
Verify Full Generic Type
The reified hasTypeOf<T>(), hasReturnTypeOf<T>() and hasReceiverTypeOf<T>() methods compare the whole type including type arguments, while the KClass overloads (e.g. hasReturnTypeOf(List::class)) ignore type arguments:
hasTypeOf<String?>() matches only a nullable type (String?), while hasTypeOf<String>() matches both String and String?. Nullability and variance (out, in) of type arguments must match exactly.
The KClass overloads (e.g. hasTypeOf(Foo::class), hasReturnTypeOf(Foo::class), hasParentOf(Foo::class)) compare fully qualified names and resolve import aliases (import com.app.Foo as Bar) and Kotlin standard library type aliases of Java types, e.g. IllegalStateException (alias of java.lang.IllegalStateException) matches IllegalStateException::class. Type aliases declared in the project (typealias Foo = Bar) are not resolved.
Last updated