### FileSpec Builder Example (Kotlin) Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-file-spec/index Demonstrates how to use the FileSpec.Builder to construct a Kotlin file. This includes adding package declarations, imports, type specifications, and member functions. ```kotlin val fileSpec = FileSpec.builder("com.example.myapp", "HelloWorld") .addFunction(FunSpec.builder("sayHello") .addStatement("println(\"Hello, World!\")") .build()) .build() ``` -------------------------------- ### Generated toString Function Example Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-name-allocator/index This example illustrates the output of the code generation process when name conflicts occur. It shows how NameAllocator appends underscores to resolve conflicts with existing names like 'sb'. ```kotlin override fun toString(): kotlin.String { val sb_ = java.lang.StringBuilder() sb_.append(ab) sb_.append(sb) return sb_.toString() } ``` -------------------------------- ### Generating a Kotlin Class with KotlinPoet Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/index Provides an example of creating a class specification using `TypeSpec`, including its name and members. ```kotlin val typeSpec = TypeSpec.classBuilder("MyClass") .addProperty("name: String") .addFunction(FunSpec.constructorBuilder().build()) .build() ``` -------------------------------- ### Add File Comment in KotlinPoet Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-file-spec/-builder/index Adds a comment to the file-site of the generated Kotlin file. This comment is prefixed to the start of the file. ```kotlin fun addFileComment(format: String, vararg args: Any): FileSpec.Builder ``` -------------------------------- ### MemberName Constructors - KotlinPoet Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-member-name/index Provides examples of the various constructors available for the MemberName class in KotlinPoet, covering initialization with package name, simple name, enclosing class name, and extension status. ```kotlin constructor(packageName: String, simpleName: String) ``` ```kotlin constructor(packageName: String, simpleName: String, isExtension: Boolean) ``` ```kotlin constructor(enclosingClassName: ClassName, simpleName: String) ``` ```kotlin constructor( enclosingClassName: ClassName, simpleName: String, isExtension: Boolean) ``` ```kotlin constructor(packageName: String, operator: KOperator) ``` ```kotlin constructor(enclosingClassName: ClassName, operator: KOperator) ``` -------------------------------- ### Begin Control Flow in FunSpec Builder (Kotlin) Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-fun-spec/-builder/index Starts a control flow block (e.g., 'if', 'for', 'while') in the function body. Supports formatted strings with arguments. ```kotlin fun beginControlFlow(controlFlow: String, vararg args: Any?): FunSpec.Builder ``` -------------------------------- ### KotlinPoet Companion: Script Builder Function Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-file-spec/-companion/index Provides a static method in the Companion object for creating a `FileSpec.Builder` specifically for Kotlin script files. This function takes a file name and an optional package name, simplifying the setup for script generation. ```kotlin import com.squareup.kotlinpoet.FileSpec // Assuming 'Companion' is accessible within the scope where this is used // Example usage: val scriptBuilder: FileSpec.Builder = Companion.scriptBuilder("MyScript.kts", "com.example.scripts") // Example without package name: val scriptBuilderNoPackage: FileSpec.Builder = Companion.scriptBuilder("AnotherScript.kts") ``` -------------------------------- ### KotlinPoet Companion: Get Function Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-file-spec/-companion/index Offers a static method in the Companion object to create a complete `FileSpec` instance. This method takes a package name and a `TypeSpec` as input, allowing for the direct generation of a `FileSpec` without explicitly using a builder. This is useful for simpler file generation scenarios. ```kotlin import com.squareup.kotlinpoet.FileSpec import com.squareup.kotlinpoet.TypeSpec // Assuming 'Companion' is accessible within the scope where this is used // Example usage: val typeSpec = TypeSpec.classBuilder("MyDataClass") .addProperty("name: String") .build() val fileSpec: FileSpec = Companion.get("com.example.data", typeSpec) ``` -------------------------------- ### Get KSP Dependencies for FileSpec (Kotlin) Source: https://square.github.io/kotlinpoet/1.x/interop-ksp/ksp/com.squareup.kotlinpoet.ksp/index Generates KSP Dependencies for a FileSpec, including originating KSFiles, for use with writeTo. ```kotlin fun FileSpec.kspDependencies(aggregating: Boolean, originatingKSFiles: Iterable = originatingKSFiles()): Dependencies ``` -------------------------------- ### GET /websites/square_github_io_kotlinpoet/allAnnotations Source: https://square.github.io/kotlinpoet/1.x/interop-kotlin-metadata/kotlin-metadata/com.squareup.kotlinpoet.metadata.specs/-method-data/all-annotations Retrieves a collection of all annotations on a method, considering optional use site targets and reified type parameters. ```APIDOC ## GET /websites/square_github_io_kotlinpoet/allAnnotations ### Description Retrieves a collection of all annotations on this method, including any derived from jvmModifiers, isSynthetic, and exceptions. ### Method GET ### Endpoint /websites/square_github_io_kotlinpoet/allAnnotations ### Parameters #### Query Parameters - **useSiteTarget** (AnnotationSpec.UseSiteTarget?) - Optional - An optional UseSiteTarget that all annotations on this method should use. - **containsReifiedTypeParameter** (Boolean) - Optional - An optional boolean indicating if any type parameters on this function are `reified`, which are implicitly synthetic. ### Response #### Success Response (200) - **annotations** (Collection) - A collection of all annotations on this method. #### Response Example ```json { "annotations": [ { "name": "ExampleAnnotation", "parameters": { "value": "example" } } ] } ``` ``` -------------------------------- ### ClassName Constructor (String, List) Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-class-name/index Constructs a ClassName from a package name and a list of simple names. Example: 'java.util', ['Map', 'Entry'] creates 'Map.Entry'. ```kotlin constructor(packageName: String, simpleNames: List) ``` -------------------------------- ### Get ParameterSpecs from ExecutableElement (KotlinPoet) Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-parameter-spec/-companion/index Extracts a list of ParameterSpec objects from an ExecutableElement. Similar to the 'get' function, it's marked with @DelicateKotlinPoetApi. ```kotlin @DelicateKotlinPoetApi(message = "Element APIs don't give complete information on Kotlin types. Consider using the kotlinpoet-metadata APIs instead.") @JvmStatic fun parametersOf(method: ExecutableElement): List ``` -------------------------------- ### Declare Parameters with KotlinPoet Source: https://square.github.io/kotlinpoet/parameters Demonstrates how to define parameters for methods and constructors using KotlinPoet. It shows the use of ParameterSpec.builder() for creating individual parameters with default values and FunSpec.addParameter() for adding them to a function specification. The example illustrates generating Kotlin code with parameters. ```kotlin val android = ParameterSpec.builder("android", String::class) .defaultValue("\"pie\"") .build() val welcomeOverlords = FunSpec.builder("welcomeOverlords") .addParameter(android) .addParameter("robot", String::class) .build() ``` ```kotlin fun welcomeOverlords(android: String = "pie", robot: String) { } ``` -------------------------------- ### ClassName Constructor (String, vararg String) Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-class-name/index Constructs a ClassName from a package name and a variable number of simple names. Example: 'java.util', 'Map', 'Entry' creates 'Map.Entry'. ```kotlin constructor(packageName: String, vararg simpleNames: String) ``` -------------------------------- ### LambdaTypeName Creation Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-lambda-type-name/-companion/index This section covers the different overloaded 'get' functions in the Companion object used to create LambdaTypeName instances. These functions allow for specifying receiver types, parameters (as ParameterSpec or TypeName), return types, and context receivers/parameters. ```APIDOC ## Companion.get for LambdaTypeName ### Description Functions to create a LambdaTypeName with a specified return type and parameters. Overloads support different ways to define parameters (ParameterSpec or TypeName) and optional receiver types. ### Method `companion object` (static methods in JVM) ### Endpoint N/A (Class Method) ### Parameters #### Function: get(receiver: TypeName?, vararg parameters: ParameterSpec, returnType: TypeName) - **receiver** (TypeName?) - Optional - The receiver type for the lambda. - **parameters** (vararg ParameterSpec) - Required - The parameters of the lambda. - **returnType** (TypeName) - Required - The return type of the lambda. #### Function: get(receiver: TypeName?, vararg parameters: TypeName, returnType: TypeName) - **receiver** (TypeName?) - Optional - The receiver type for the lambda. - **parameters** (vararg TypeName) - Required - The parameters of the lambda. - **returnType** (TypeName) - Required - The return type of the lambda. #### Function: get(receiver: TypeName?, parameters: List, returnType: TypeName) - **receiver** (TypeName?) - Optional - The receiver type for the lambda. - **parameters** (List) - Required - The parameters of the lambda. - **returnType** (TypeName) - Required - The return type of the lambda. #### Function: get(receiver: TypeName?, parameters: List, returnType: TypeName, contextReceivers: List, contextParameters: List) - **receiver** (TypeName?) - Optional - The receiver type for the lambda. - **parameters** (List) - Required - The parameters of the lambda. - **returnType** (TypeName) - Required - The return type of the lambda. - **contextReceivers** (List) - Optional - Context receivers for the lambda. - **contextParameters** (List) - Optional - Context parameters for the lambda. ### Request Example ```kotlin // Example using ParameterSpec val lambdaType1 = LambdaTypeName.get( parameters = arrayOf(ParameterSpec.builder("it").build()), returnType = STRING ) // Example using TypeName val lambdaType2 = LambdaTypeName.get( parameters = arrayOf(STRING), returnType = INT ) // Example with receiver and context receivers val lambdaType3 = LambdaTypeName.get( receiver = ClassName.get("com.example", "MyReceiver"), parameters = arrayOf(ParameterSpec.builder("name").build()), returnType = VOID, contextReceivers = listOf(ClassName.get("com.example", "MyContext")) ) ``` ### Response #### Success Response (200) Returns a LambdaTypeName object representing the defined lambda signature. ``` -------------------------------- ### KotlinPoet AnnotationSpec Get Functions (JVM) Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-annotation-spec/-companion/index Provides functions to retrieve AnnotationSpec instances using AnnotationMirror or Java Annotation with optional default value inclusion for JVM environments. ```kotlin @DelicateKotlinPoetApi(message = "Mirror APIs don't give complete information on Kotlin types. Consider using the kotlinpoet-metadata APIs instead.") fun get(annotation: AnnotationMirror): AnnotationSpec ``` ```kotlin @DelicateKotlinPoetApi(message = "Java reflection APIs don't give complete information on Kotlin types. Consider using the kotlinpoet-metadata APIs instead.") @JvmOverloads fun get( annotation: Annotation, includeDefaultValues: Boolean = false): AnnotationSpec ``` -------------------------------- ### TypeParameterResolver Get Function Source: https://square.github.io/kotlinpoet/1.x/interop-ksp/ksp/com.squareup.kotlinpoet.ksp/-type-parameter-resolver/index Abstract operator function 'get' for TypeParameterResolver, which takes a String index and returns a TypeVariableName. ```kotlin abstract operator fun get(index: String): TypeVariableName ``` -------------------------------- ### Generating a Kotlin File with KotlinPoet Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/index Demonstrates how to create a basic Kotlin file using `FileSpec`, including package declaration and top-level functions. ```kotlin val fileSpec = FileSpec.builder("com.example.myapp", "HelloWorld") .addFunction(FunSpec.builder("helloWorld") .addStatement("println(\"Hello, World!\")") .build()) .build() // To get the code as a string: // println(fileSpec.toString()) ``` -------------------------------- ### Generate HelloWorld file with KotlinPoet Source: https://square.github.io/kotlinpoet/index This code snippet demonstrates how to use KotlinPoet to programmatically generate a Kotlin source file named 'HelloWorld'. It defines a 'Greeter' class with a constructor and a 'greet' method, along with a 'main' function to instantiate and use the class. This is useful for tasks like annotation processing. ```kotlin val greeterClass = ClassName("", "Greeter") val file = FileSpec.builder("", "HelloWorld") .addType( TypeSpec.classBuilder("Greeter") .primaryConstructor( FunSpec.constructorBuilder() .addParameter("name", String::class) .build() ) .addProperty( PropertySpec.builder("name", String::class) .initializer("name") .build() ) .addFunction( FunSpec.builder("greet") .addStatement("println(%P)", "Hello, \$name") .build() ) .build() ) .addFunction( FunSpec.builder("main") .addParameter("args", String::class, VARARG) .addStatement("%T(args[0]).greet()", greeterClass) .build() ) .build() file.writeTo(System.out) ``` -------------------------------- ### PropertySpec Functions Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-property-spec/index Overview of functions available for PropertySpec instances. ```APIDOC ## PropertySpec Functions ### Description Functions that can be called on `PropertySpec` instances. ### Method N/A (Functions) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **equals(other: Any?)** (Boolean) - Compares this `PropertySpec` with another object. - **hashCode()** (Int) - Returns the hash code for this `PropertySpec`. - **tag(type: Class): T?** (T?) - Retrieves a tag associated with the specified class type. - **tag(type: KClass): T?** (T?) - Retrieves a tag associated with the specified KClass type. - **tag(): T?** (T?) - Retrieves a tag of a generic type T. - **toBuilder(name: String = this.name, type: TypeName = this.type): PropertySpec.Builder** (PropertySpec.Builder) - Creates a `Builder` from the current `PropertySpec`, optionally updating name and type. - **toString()** (String) - Returns a string representation of the `PropertySpec`. #### Response Example N/A ``` -------------------------------- ### NameAllocator get Function Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-name-allocator/index Retrieves the allocated name for a given tag. The tag must have been previously used with NameAllocator.newName. ```kotlin operator fun get(tag: Any): String ``` -------------------------------- ### Builder Class Overview Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-fun-spec/-builder/index Provides an overview of the Builder class and its properties. ```APIDOC ## Builder Class ### Description The Builder class is a core component in KotlinPoet for constructing code elements. It implements several interfaces to manage annotations, context parameters, originating elements, and more. ### Properties - **annotations** (MutableList) - A mutable list of AnnotationSpec instances associated with this builder. - **contextParameters** (MutableList) - A mutable list of current context parameters. - **contextReceiverTypes** (MutableList) - A mutable list of TypeName instances representing context receiver types. - **kdoc** (CodeBlock.Builder) - A CodeBlock.Builder for managing KDoc comments. - **modifiers** (MutableList) - A mutable list of KModifier instances. - **originatingElements** (MutableList) - A mutable list of originating elements. - **parameters** (MutableList) - A mutable list of ParameterSpec instances. - **tags** (MutableMap, Any>) - A mutable map for storing tags associated with this builder. - **typeVariables** (MutableList) - A mutable list of TypeVariableName instances. ``` -------------------------------- ### JvmModifier Kotlin Interface Source: https://square.github.io/kotlinpoet/1.x/interop-kotlin-metadata/kotlin-metadata/com.squareup.kotlinpoet.metadata.specs/index Represents a JVM modifier that is expressed as an annotation in Kotlin but as a modifier in bytecode. Examples include @JvmStatic or @JvmSynthetic. ```kotlin interface JvmModifier ``` -------------------------------- ### Builder Methods Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-context-parameterizable/-builder/index This section details the methods available on the Builder interface for managing context parameters. ```APIDOC ## Builder Interface ### Description The Builder interface is analogous to `ContextParameterizable` types and facilitates the management of context parameters during type generation. ### Methods #### `contextParameter(contextParameter: ContextParameter)` * **Description**: Adds the given `ContextParameter` to this type's list of context parameters. * **Returns**: The builder instance (`T`) for chaining. #### `contextParameter(type: TypeName)` * **Description**: Adds a context parameter with the name "_" and the specified `TypeName`. * **Returns**: The builder instance (`T`) for chaining. #### `contextParameter(name: String, type: TypeName)` * **Description**: Adds a context parameter with the given name and `TypeName`. * **Returns**: The builder instance (`T`) for chaining. #### `contextParameter(name: String, type: Type)` * **Description**: Adds a context parameter with the given name and `Type` (from Java reflection). Note: This method is marked with `@DelicateKotlinPoetApi` due to potential limitations with Java reflection for Kotlin types. * **Returns**: The builder instance (`T`) for chaining. #### `contextParameter(name: String, type: KClass<*>)` * **Description**: Adds a context parameter with the given name and `KClass`. * **Returns**: The builder instance (`T`) for chaining. #### `contextParameters(parameters: Iterable)` * **Description**: Adds the given collection of `ContextParameter` objects to this type's list of context parameters. * **Returns**: The builder instance (`T`) for chaining. ### Properties #### `contextParameters: MutableList` * **Description**: A mutable list containing the current context parameters held by this builder. ``` -------------------------------- ### Kotlin Builder Constructor Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-code-block/-builder/index Initializes a new instance of the Builder class. This is the primary way to create a builder object for constructing code. ```kotlin constructor() ``` -------------------------------- ### Get Originating KSFiles from FileSpec (Kotlin) Source: https://square.github.io/kotlinpoet/1.x/interop-ksp/ksp/com.squareup.kotlinpoet.ksp/index Retrieves the list of originating KSFiles associated with a FileSpec, useful for KSP incremental processing. ```kotlin fun FileSpec.originatingKSFiles(): List ``` -------------------------------- ### Get Tagged Value (KotlinPoet) Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com Retrieves a tag associated with an object using the object itself as the key. Returns null if no tag is found for the given key. ```kotlin inline fun Taggable.tag(): T? ``` -------------------------------- ### Get Originating KSFiles from Specs (Kotlin) Source: https://square.github.io/kotlinpoet/1.x/interop-ksp/ksp/com.squareup.kotlinpoet.ksp/index Retrieves the originating KSFiles from individual KotlinPoet specs (FunSpec, PropertySpec, TypeAliasSpec, TypeSpec) for KSP. ```kotlin fun FunSpec.originatingKSFiles(): List fun PropertySpec.originatingKSFiles(): List fun TypeAliasSpec.originatingKSFiles(): List fun TypeSpec.originatingKSFiles(): List ``` -------------------------------- ### ContextParameter Methods (Kotlin) Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-context-parameter/index Outlines the standard methods available for the ContextParameter class, such as equals, hashCode, and toString, which are essential for object comparison and representation. ```kotlin open operator override fun equals(other: Any?): Boolean ``` ```kotlin open override fun hashCode(): Int ``` ```kotlin open override fun toString(): String ``` -------------------------------- ### Get Context Parameters - Kotlin Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-context-parameterizable/-builder/index Retrieves a mutable list of the current context parameters contained within this builder. This property is declared in the Builder interface. ```kotlin abstract val contextParameters: MutableList ``` -------------------------------- ### FunSpec Builder Methods Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-fun-spec/-builder/index Provides an overview of the methods used to build and configure a FunSpec, including adding annotations, code blocks, comments, parameters, modifiers, and control flow. ```APIDOC ## FunSpec Builder Methods ### Description Methods for configuring Kotlin function specifications using the FunSpec builder. ### addAnnotation Adds annotations to the function. - **addAnnotation(annotationSpec: AnnotationSpec)**: Adds a specific AnnotationSpec. - **addAnnotation(annotation: ClassName)**: Adds an annotation using ClassName. - **addAnnotation(annotation: Class<*>)**: Adds an annotation using a Java Class (uses reflection, consider metadata APIs). - **addAnnotation(annotation: KClass<*>)**: Adds an annotation using a Kotlin KClass. ### addAnnotations Adds multiple annotations from an iterable. - **addAnnotations(annotationSpecs: Iterable)**: Adds a collection of AnnotationSpecs. ### addCode Adds code blocks or formatted strings to the function body. - **addCode(codeBlock: CodeBlock)**: Adds a pre-defined CodeBlock. - **addCode(format: String, vararg args: Any?)**: Adds formatted code with arguments. ### addComment Adds a comment to the function. - **addComment(format: String, vararg args: Any)**: Adds a formatted comment. ### addKdoc Adds KDoc documentation to the function. - **addKdoc(block: CodeBlock)**: Adds KDoc from a CodeBlock. - **addKdoc(format: String, vararg args: Any)**: Adds formatted KDoc. ### addModifiers Adds modifiers to the function. - **addModifiers(vararg modifiers: KModifier)**: Adds modifiers individually. - **addModifiers(modifiers: Iterable)**: Adds modifiers from an iterable. ### addNamedCode Adds code with named arguments. - **addNamedCode(format: String, args: Map)**: Adds formatted code with named arguments. ### addOriginatingElement Specifies originating elements for the function. - **addOriginatingElement(originatingElement: Element)**: Adds a single originating element. ### addParameter Adds parameters to the function. - **addParameter(parameterSpec: ParameterSpec)**: Adds a ParameterSpec. - **addParameter(name: String, type: TypeName, vararg modifiers: KModifier)**: Adds a parameter with name, type, and modifiers. - **addParameter(name: String, type: TypeName, modifiers: Iterable)**: Adds a parameter with name, type, and modifiers from an iterable. - **addParameter(name: String, type: Type, vararg modifiers: KModifier)**: Adds a parameter with name, Java Type, and modifiers. - **addParameter(name: String, type: Type, modifiers: Iterable)**: Adds a parameter with name, Java Type, and modifiers from an iterable. - **addParameter(name: String, type: KClass<*>, vararg modifiers: KModifier)**: Adds a parameter with name, KClass type, and modifiers. - **addParameter(name: String, type: KClass<*>, modifiers: Iterable)**: Adds a parameter with name, KClass type, and modifiers from an iterable. ### addParameters Adds multiple parameters from an iterable. - **addParameters(parameterSpecs: Iterable)**: Adds a collection of ParameterSpecs. ### addStatement Adds a statement to the function body. - **addStatement(format: String, vararg args: Any)**: Adds a formatted statement. ### addTypeVariable Adds a type variable to the function. - **addTypeVariable(typeVariable: TypeVariableName)**: Adds a single type variable. ### addTypeVariables Adds multiple type variables from an iterable. - **addTypeVariables(typeVariables: Iterable)**: Adds a collection of type variables. ### beginControlFlow Starts a control flow block (e.g., if, for, while). - **beginControlFlow(controlFlow: String, vararg args: Any?)**: Begins a control flow block with formatted arguments. ### build Finalizes the FunSpec construction. - **build()**: Returns the constructed FunSpec. ### callSuperConstructor Calls the superclass constructor. - **callSuperConstructor(vararg args: CodeBlock = emptyArray())**: Calls with CodeBlock arguments. - **callSuperConstructor(vararg args: String)**: Calls with String arguments. - **callSuperConstructor(args: Iterable)**: Calls with an iterable of CodeBlocks. - **callSuperConstructor(args: List)**: Calls with a list of CodeBlocks. ### callThisConstructor Calls another constructor of the same class. - **callThisConstructor(vararg args: CodeBlock = emptyArray())**: Calls with CodeBlock arguments. - **callThisConstructor(vararg args: String)**: Calls with String arguments. - **callThisConstructor(args: Iterable)**: Calls with an iterable of CodeBlocks. - **callThisConstructor(args: List)**: Calls with a list of CodeBlocks. ### clearBody Clears the current body of the function. - **clearBody()**: Resets the function body. ### contextParameter Adds context parameters to the function. - **contextParameter(contextParameter: ContextParameter)**: Adds a specific ContextParameter. - **contextParameter(type: TypeName)**: Adds a context parameter with default name `_`. - **contextParameter(name: String, type: TypeName)**: Adds a context parameter with specified name and type. - **contextParameter(name: String, type: Type)**: Adds a context parameter with specified name and Java Type. - **contextParameter(name: String, type: KClass<*>)**: Adds a context parameter with specified name and KClass type. ### contextParameters Adds multiple context parameters. - **contextParameters(parameters: Iterable)**: Adds a collection of ContextParameters. ### contextReceivers Adds context receivers to the function. - **contextReceivers(vararg receiverTypes: TypeName)**: Adds receiver types individually. - **contextReceivers(receiverTypes: Iterable)**: Adds receiver types from an iterable. ``` -------------------------------- ### Create LambdaTypeName with Parameters (Kotlin) Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-lambda-type-name/-companion/get Creates a LambdaTypeName with a given return type and a list of parameters. This overload is useful for defining simple lambda types. ```kotlin @JvmStatic fun get( receiver: TypeName? = null, parameters: List = emptyList(), returnType: TypeName): LambdaTypeName ``` -------------------------------- ### Generate Kotlin Constructor with Parameters and Statements Source: https://square.github.io/kotlinpoet/constructors Demonstrates how to create a constructor with parameters and add initialization statements using KotlinPoet's FunSpec.constructorBuilder(). This is useful for setting up class properties during instantiation. ```kotlin val flux = FunSpec.constructorBuilder() .addParameter("greeting", String::class) .addStatement("this.%N = %N", "greeting", "greeting") .build() val helloWorld = TypeSpec.classBuilder("HelloWorld") .addProperty("greeting", String::class, KModifier.PRIVATE) .addFunction(flux) .build() ``` -------------------------------- ### PropertySpec Properties Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-property-spec/index Details of the properties available for configuring a PropertySpec. ```APIDOC ## PropertySpec Properties ### Description Properties that can be configured for a generated property declaration. ### Method N/A (Class properties) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **annotations** (List) - Annotations for the property. - **contextParameters** (List) - Context parameters for the property. - **contextReceiverTypes** (List) - Context receiver types for the property. - **delegated** (Boolean) - Indicates if the property is delegated. - **getter** (FunSpec?) - The getter specification for the property. - **initializer** (CodeBlock?) - The initializer code block for the property. - **kdoc** (CodeBlock) - KDoc for the property. - **modifiers** (Set) - Modifiers for the property. - **mutable** (Boolean) - Indicates if the property is mutable. - **name** (String) - The name of the property. - **originatingElements** (List) - Originating elements for the property. - **receiverType** (TypeName?) - The receiver type for the property. - **setter** (FunSpec?) - The setter specification for the property. - **tags** (Map, Any>) - Tags associated with the property. - **type** (TypeName) - The type of the property. - **typeVariables** (List) - Type variables for the property. #### Response Example N/A ``` -------------------------------- ### PropertySpec Builder Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-property-spec/index Information about the PropertySpec builder for creating new property specifications. ```APIDOC ## PropertySpec Builder ### Description Provides a fluent interface for constructing `PropertySpec` objects. ### Method N/A (Class) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **Builder** (Type) - The type of the builder itself, allowing for chained method calls. #### Response Example N/A ``` -------------------------------- ### Creating a Kotlin Function with KotlinPoet Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/index Shows how to define a function specification using `FunSpec`, including adding parameters and statements. ```kotlin val funSpec = FunSpec.builder("greet") .addParameter("name", String::class) .addStatement("println(\"Hello, $name!\")") .build() ``` -------------------------------- ### Get TypeName from Reified Type (KotlinPoet) Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com Returns a TypeName equivalent of a reified type parameter T, potentially using kotlin-reflect. This function infers the type at compile time. ```kotlin inline fun typeNameOf(): TypeName ``` -------------------------------- ### KotlinPoet Extensions for KSP Originating Files Source: https://square.github.io/kotlinpoet/1.x/interop-ksp/ksp/com.squareup.kotlinpoet.ksp/index Provides extensions for `FunSpec.Builder`, `PropertySpec.Builder`, `TypeAliasSpec.Builder`, and `TypeSpec.Builder` to add originating KSFiles. Also includes functions to retrieve originating KSFiles and manage KSP dependencies. ```APIDOC ## FileSpec ### Functions - **`kspDependencies(aggregating: Boolean, originatingKSFiles: Iterable = originatingKSFiles()): Dependencies`**: Returns a KSP Dependencies component for incremental processing. - **`originatingKSFiles(): List`**: Returns the list of originating KSFiles associated with this FileSpec. - **`writeTo(codeGenerator: CodeGenerator, dependencies: Dependencies)`**: Writes this FileSpec to a code generator with specified dependencies. - **`writeTo(codeGenerator: CodeGenerator, aggregating: Boolean, originatingKSFiles: Iterable = originatingKSFiles())`**: Writes this FileSpec to a code generator with specified originating KSFiles. ## FunSpec.Builder ### Functions - **`addOriginatingKSFile(ksFile: KSFile): FunSpec.Builder`**: Adds an originating KSFile to this builder. - **`originatingKSFiles(): List`**: Returns the list of originating KSFiles associated with this FunSpec. ## PropertySpec.Builder ### Functions - **`addOriginatingKSFile(ksFile: KSFile): PropertySpec.Builder`**: Adds an originating KSFile to this builder. - **`originatingKSFiles(): List`**: Returns the list of originating KSFiles associated with this PropertySpec. ## TypeAliasSpec.Builder ### Functions - **`addOriginatingKSFile(ksFile: KSFile): TypeAliasSpec.Builder`**: Adds an originating KSFile to this builder. - **`originatingKSFiles(): List`**: Returns the list of originating KSFiles associated with this TypeAliasSpec. ## TypeSpec.Builder ### Functions - **`addOriginatingKSFile(ksFile: KSFile): TypeSpec.Builder`**: Adds an originating KSFile to this builder. - **`originatingKSFiles(): List`**: Returns the list of originating KSFiles associated with this TypeSpec. ``` -------------------------------- ### Get TypeName from Reflection Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-type-name/index Explains how to convert a reflection type into a TypeName instance. This enables the use of KotlinPoet's type modeling capabilities with existing reflection code. ```kotlin val reflectionType: kotlin.reflect.KClass<*> = String::class val typeName = reflectionType.asTypeName() ``` -------------------------------- ### Build Project with Gradle Source: https://square.github.io/kotlinpoet/contributing Command to clean and build the KotlinPoet project using Gradle. This ensures the code compiles correctly before submission. ```shell ./gradlew clean build ``` -------------------------------- ### Create LambdaTypeName with Vararg ParameterSpecs (Kotlin) Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-lambda-type-name/-companion/get Generates a LambdaTypeName with a return type and a variable number of ParameterSpec objects. This overload allows for more detailed parameter definitions. ```kotlin @JvmStatic fun get( receiver: TypeName? = null, vararg parameters: ParameterSpec = emptyArray(), returnType: TypeName): LambdaTypeName ``` -------------------------------- ### Kotlin Builder State and Build Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-code-block/-builder/index Includes functions for checking the state of the builder and finalizing the code construction. `isEmpty` and `isNotEmpty` check if any code has been added, while `build` generates the final CodeBlock. ```kotlin fun build(): CodeBlock ``` ```kotlin fun isEmpty(): Boolean ``` ```kotlin fun isNotEmpty(): Boolean ``` ```kotlin fun clear(): CodeBlock.Builder ``` -------------------------------- ### Create LambdaTypeName with Context Receivers (Kotlin) Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-lambda-type-name/-companion/get Generates a LambdaTypeName with a specified return type, parameters, and context receivers. Requires KotlinPoet's TypeName and ParameterSpec. ```kotlin @JvmStatic fun get( receiver: TypeName? = null, parameters: List = emptyList(), returnType: TypeName, contextReceivers: List = emptyList(), contextParameters: List = emptyList()): LambdaTypeName ``` -------------------------------- ### ConstructorData Properties (Kotlin) Source: https://square.github.io/kotlinpoet/1.x/interop-kotlin-metadata/kotlin-metadata/com.squareup.kotlinpoet.metadata.specs/-constructor-data/index Lists the properties of the ConstructorData class, providing details on annotations, exceptions, synthetic status, JVM modifiers, and parameter annotations. ```kotlin val allAnnotations: Collection ``` ```kotlin val exceptions: List ``` ```kotlin val isSynthetic: Boolean ``` ```kotlin val jvmModifiers: Set ``` ```kotlin val parameterAnnotations: Map> ``` -------------------------------- ### Defining a Kotlin Property with KotlinPoet Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/index Illustrates the creation of a property specification using `PropertySpec`, specifying its name, type, and initial value. ```kotlin val propertySpec = PropertySpec.builder("myProperty", Int::class) .initializer("42") .build() ``` -------------------------------- ### Get ParameterSpec from VariableElement (KotlinPoet) Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-parameter-spec/-companion/index Retrieves a ParameterSpec directly from a VariableElement. This function is marked with @DelicateKotlinPoetApi, suggesting potential limitations compared to metadata APIs. ```kotlin @DelicateKotlinPoetApi(message = "Element APIs don't give complete information on Kotlin types. Consider using the kotlinpoet-metadata APIs instead.") @JvmStatic fun get(element: VariableElement): ParameterSpec ``` -------------------------------- ### Create LambdaTypeName with Vararg TypeNames (Kotlin) Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-lambda-type-name/-companion/get Constructs a LambdaTypeName using a return type and a variable number of TypeName parameters. This provides flexibility in defining lambda signatures. ```kotlin @JvmStatic fun get( receiver: TypeName? = null, vararg parameters: TypeName = emptyArray(), returnType: TypeName): LambdaTypeName ``` -------------------------------- ### Create Constructor Builder Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-fun-spec/-companion/index Creates a new builder specifically for constructing constructors. This function is intended for JVM usage. ```kotlin @JvmStatic fun constructorBuilder(): FunSpec.Builder ``` -------------------------------- ### ClassName plusParameter Function in Kotlin Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-class-name/index Creates a ParameterizedTypeName by applying a single type argument to the current ClassName. This JVM-specific function is annotated with @JvmStatic and @JvmName("get"). ```kotlin @JvmStatic @JvmName(name = "get") fun ClassName.plusParameter(typeArgument: TypeName): ParameterizedTypeName ``` -------------------------------- ### Get Context Receiver Types (Kotlin) Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-context-receivable/-builder/index This code shows how to access the mutable list of context receiver types associated with a builder. This property holds the originating elements for the builder. ```kotlin abstract val contextReceiverTypes: MutableList ``` -------------------------------- ### MethodData Constructor (Kotlin) Source: https://square.github.io/kotlinpoet/1.x/interop-kotlin-metadata/kotlin-metadata/com.squareup.kotlinpoet.metadata.specs/-method-data/index Provides the primary constructor for the MethodData class. It initializes all properties of the class, allowing for the creation of MethodData objects with specific method details. ```kotlin constructor( annotations: List, parameterAnnotations: Map>, isSynthetic: Boolean, jvmModifiers: Set, isOverride: Boolean, exceptions: List ) ``` -------------------------------- ### ContextParameter Constructors (Kotlin) Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-context-parameter/index Provides two constructors for creating ContextParameter instances: one that infers the name and another that explicitly sets both name and type. ```kotlin constructor(type: TypeName) ``` ```kotlin constructor(name: String, type: TypeName) ``` -------------------------------- ### FileData Constructor (Kotlin) Source: https://square.github.io/kotlinpoet/1.x/interop-kotlin-metadata/kotlin-metadata/com.squareup.kotlinpoet.metadata.specs/-file-data/index Provides the constructor signature for the FileData data class. It details the parameters required to instantiate FileData, mirroring the data class properties. ```kotlin constructor( declarationContainer: KmPackage, annotations: Collection, properties: Map, methods: Map, className: ClassName, jvmName: String? = if (!className.simpleName.endsWith("Kt")) className.simpleName else null) ``` -------------------------------- ### Get TypeName from Type Mirror in Annotation Processor Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-type-name/index Shows how to obtain a TypeName instance for a given type mirror within an annotation processor. This is crucial for analyzing and manipulating types during the compilation process. ```kotlin val typeMirror: TypeMirror = ... // Obtained from annotation processing val typeName = typeMirror.asTypeName() ``` -------------------------------- ### NameAllocator Constructors Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-name-allocator/index Constructors for creating a new NameAllocator instance. ```APIDOC ## NameAllocator Constructor ### Description Creates a new NameAllocator instance. ### Parameters #### Optional Parameters - **preallocateKeywords** (Boolean) - If true, preallocates keywords to prevent their use. ### Method `constructor()` `constructor(preallocateKeywords: Boolean)` ``` -------------------------------- ### ClassName parameterizedBy Functions in Kotlin Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-class-name/index Creates a ParameterizedTypeName by applying type arguments to the current ClassName. Overloaded to accept varargs or a List of TypeName. Both are annotated with @JvmStatic and @JvmName("get"). ```kotlin @JvmStatic @JvmName(name = "get") fun ClassName.parameterizedBy(vararg typeArguments: TypeName): ParameterizedTypeName ``` ```kotlin @JvmStatic @JvmName(name = "get") fun ClassName.parameterizedBy(typeArguments: List): ParameterizedTypeName ``` -------------------------------- ### Create Kotlin Object with Properties and Functions - KotlinPoet Source: https://square.github.io/kotlinpoet/objects Demonstrates creating a singleton object named 'HelloWorld' with a property 'buzz' and a function 'beep' using KotlinPoet. This is useful for defining constants or utility functions within a singleton scope. ```kotlin val helloWorld = TypeSpec.objectBuilder("HelloWorld") .addProperty( PropertySpec.builder("buzz", String::class) .initializer("%S", "buzz") .build() ) .addFunction( FunSpec.builder("beep") .addStatement("println(%S)", "Beep!") .build() ) .build() ``` -------------------------------- ### Generate class with non-existent type import using %T Source: https://square.github.io/kotlinpoet/t-for-types Shows how to use %T with a ClassName for a type that doesn't exist at compile time, ensuring KotlinPoet correctly generates the import. This example references a 'Hoverboard' class. ```kotlin val hoverboard = ClassName("com.mattel", "Hoverboard") val tomorrow = FunSpec.builder("tomorrow") .returns(hoverboard) .addStatement("return %T()", hoverboard) .build() ``` -------------------------------- ### MemberName Functions Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-member-name/index Documentation for the reference and toString functions available on MemberName objects. ```APIDOC ## MemberName Functions ### Description Provides methods to generate code references and string representations for `MemberName` objects. ### Functions 1. **`reference(): CodeBlock`** * **Description**: Returns a `CodeBlock` representing a callable reference to this member. It includes the enclosing class name and the reference operator `::`, followed by the simple name or fully-qualified name. * **Method**: `fun` 2. **`toString(): String`** * **Description**: Returns a string representation of the `MemberName`. ``` -------------------------------- ### Clear File Body Specification Builder Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-file-spec/-builder/index Resets the body of the FileSpec builder, effectively clearing any previously added code or content. This is useful for starting a new code block or resetting the builder state. ```kotlin fun clearBody(): FileSpec.Builder ``` -------------------------------- ### ClassName enclosingClassName Function in Kotlin Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-class-name/index Retrieves the enclosing ClassName for a nested class, returning null if the class is not nested. For example, it returns 'Map' for 'Map.Entry'. This JVM-specific function is essential for navigating class hierarchies. ```kotlin fun enclosingClassName(): ClassName? ``` -------------------------------- ### PropertySpec Companion Object Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-property-spec/index Details regarding the companion object of PropertySpec. ```APIDOC ## PropertySpec Companion Object ### Description Companion object for `PropertySpec`, potentially containing utility methods or constants. ### Method N/A (Object) ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example N/A ### Response #### Success Response (200) - **Companion** (Object) - The companion object itself. #### Response Example N/A ``` -------------------------------- ### TypeName Class Overview Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-type-name/index Provides an overview of the TypeName class, its purpose, and how it models Kotlin types. ```APIDOC ## TypeName ### Description `jvm sealed class TypeName : Taggable, Annotatable` Represents any type in Kotlin's type system. This class identifies simple types like `Int` and `String`, nullable types like `Int?`, composite types like `Array` and `Set`, and unassignable types like `Unit`. Type names are dumb identifiers only and do not model the values they name. For example, the type name for `kotlin.List` doesn't know about the `size()` function, the fact that lists are collections, or even that it accepts a single type parameter. Instances of this class are immutable value objects that implement `equals()` and `hashCode()` properly. ### Referencing Existing Types In an annotation processor you can get a type name instance for a type mirror by calling `asTypeName`. In reflection code, you can use `asTypeName`. ### Defining New Types Create new reference types like `com.example.HelloWorld` with `ClassName.bestGuess`. To build composite types like `Set`, use the factory methods on `ParameterizedTypeName`, `TypeVariableName`, and `WildcardTypeName`. ### Inheritors - ClassName - Dynamic - LambdaTypeName - ParameterizedTypeName - TypeVariableName - WildcardTypeName ### Properties - **annotations** (List) - Returns all annotations. - **isAnnotated** (Boolean) - Checks if the type is annotated. - **isNullable** (Boolean) - Checks if the type is nullable. - **tags** (Map, Any>) - Returns all tags. ### Functions - **copy**(nullable: Boolean = this.isNullable, annotations: List = this.annotations.toList()): TypeName - **copy**(nullable: Boolean = this.isNullable, annotations: List = this.annotations.toList(), tags: Map, Any> = this.tags): TypeName - **equals**(other: Any?): Boolean - **hashCode**(): Int - **jvmSuppressWildcards**(suppress: Boolean = true): TypeName - **jvmWildcard**(): TypeName - **tag**(type: Class): T? - **tag**(type: KClass): T? - **tag**(): T? - **toString**(): String ``` -------------------------------- ### Retrieve All Annotations (Kotlin) Source: https://square.github.io/kotlinpoet/1.x/interop-kotlin-metadata/kotlin-metadata/com.squareup.kotlinpoet.metadata.specs/-method-data/index A function to get all annotations associated with a method, including those derived from JVM modifiers, synthetic status, and exceptions. It allows optional filtering by use site target and a flag for reified type parameters. ```kotlin fun allAnnotations( useSiteTarget: AnnotationSpec.UseSiteTarget? = null, containsReifiedTypeParameter: Boolean = false ): Collection ``` -------------------------------- ### NameAllocator Constructor Source: https://square.github.io/kotlinpoet/1.x/kotlinpoet/kotlinpoet/com.squareup.kotlinpoet/-name-allocator/index Constructors for the NameAllocator class. The first constructor creates an instance with default settings, while the second allows pre-allocating keywords. ```kotlin constructor() constructor(preallocateKeywords: Boolean) ```