or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

annotations-and-metadata.mdcode-generation.mdfile-and-type-generation.mdfunction-and-property-generation.mdindex.mdtype-system.mdutilities.md

file-and-type-generation.mddocs/

0

# File and Type Generation

1

2

Core functionality for creating Kotlin files and type declarations including classes, interfaces, objects, and annotation classes. This forms the foundation of all code generation workflows in KotlinPoet.

3

4

## Capabilities

5

6

### File Specification

7

8

Creates and manages Kotlin source files with package declarations, imports, and top-level declarations.

9

10

```kotlin { .api }

11

/**

12

* Specification for generating .kt source files

13

*/

14

class FileSpec private constructor() {

15

companion object {

16

/** Creates a builder for a new file with the given package and file name */

17

fun builder(packageName: String, fileName: String): Builder

18

19

/** Creates a builder from a ClassName */

20

fun builder(className: ClassName): Builder

21

22

/** Creates a builder from a MemberName */

23

fun builder(memberName: MemberName): Builder

24

25

/** Creates a file spec from a package name and type spec */

26

fun get(packageName: String, typeSpec: TypeSpec): FileSpec

27

28

/** Creates a builder for a Kotlin script file (.kts) */

29

fun scriptBuilder(fileName: String, packageName: String = ""): Builder

30

}

31

32

/** Writes the file content to the provided Appendable */

33

fun writeTo(out: Appendable)

34

35

/** Writes the file to the specified directory path */

36

fun writeTo(directory: Path)

37

38

/** Writes the file to the specified directory as a File */

39

fun writeTo(directory: File)

40

41

/** Returns the generated file content as a string */

42

override fun toString(): String

43

44

/** Builder for constructing FileSpec instances */

45

class Builder {

46

/** Adds a top-level type declaration to the file */

47

fun addType(typeSpec: TypeSpec): Builder

48

49

/** Adds a top-level function to the file */

50

fun addFunction(funSpec: FunSpec): Builder

51

52

/** Adds a top-level property to the file */

53

fun addProperty(propertySpec: PropertySpec): Builder

54

55

/** Adds a type alias to the file */

56

fun addTypeAlias(typeAliasSpec: TypeAliasSpec): Builder

57

58

/** Adds an import statement */

59

fun addImport(packageName: String, names: String): Builder

60

fun addImport(className: ClassName): Builder

61

fun addImport(memberName: MemberName): Builder

62

63

/** Adds an aliased import statement */

64

fun addAliasedImport(className: ClassName, alias: String): Builder

65

fun addAliasedImport(memberName: MemberName, alias: String): Builder

66

67

/** Adds KDoc documentation to the file */

68

fun addFileComment(format: String, vararg args: Any): Builder

69

70

/** Adds an annotation to the file */

71

fun addAnnotation(annotationSpec: AnnotationSpec): Builder

72

73

/** Sets the default imports for the file */

74

fun defaultImports(vararg defaultImports: String): Builder

75

76

/** Builds the FileSpec */

77

fun build(): FileSpec

78

}

79

}

80

```

81

82

**Usage Examples:**

83

84

```kotlin

85

import com.squareup.kotlinpoet.*

86

87

// Basic file creation

88

val file = FileSpec.builder("com.example", "Generated")

89

.addFileComment("Auto-generated file - do not edit")

90

.addType(

91

TypeSpec.classBuilder("Example")

92

.addProperty(PropertySpec.builder("value", Int::class).initializer("42").build())

93

.build()

94

)

95

.build()

96

97

// File with multiple top-level declarations

98

val multiFile = FileSpec.builder("com.example.utils", "Helpers")

99

.addFunction(

100

FunSpec.builder("printMessage")

101

.addParameter("message", String::class)

102

.addStatement("println(message)")

103

.build()

104

)

105

.addProperty(

106

PropertySpec.builder("DEFAULT_MESSAGE", String::class)

107

.addModifiers(KModifier.CONST)

108

.initializer("%S", "Hello World")

109

.build()

110

)

111

.addTypeAlias(

112

TypeAliasSpec.builder("StringMap", Map::class.asClassName().parameterizedBy(String::class.asTypeName(), String::class.asTypeName()))

113

.build()

114

)

115

.build()

116

```

117

118

### Class Specification

119

120

Generates class declarations with support for all Kotlin class types and modifiers.

121

122

```kotlin { .api }

123

/**

124

* Specification for generating class, interface, object, and other type declarations

125

*/

126

class TypeSpec private constructor() {

127

companion object {

128

/** Creates a builder for a regular class */

129

fun classBuilder(name: String): Builder

130

fun classBuilder(className: ClassName): Builder

131

132

/** Creates a builder for an interface */

133

fun interfaceBuilder(name: String): Builder

134

fun interfaceBuilder(className: ClassName): Builder

135

136

/** Creates a builder for an object declaration */

137

fun objectBuilder(name: String): Builder

138

fun objectBuilder(className: ClassName): Builder

139

140

/** Creates a builder for an annotation class */

141

fun annotationBuilder(name: String): Builder

142

fun annotationBuilder(className: ClassName): Builder

143

144

/** Creates a builder for an enum class */

145

fun enumBuilder(name: String): Builder

146

fun enumBuilder(className: ClassName): Builder

147

148

/** Creates a builder for a companion object */

149

fun companionObjectBuilder(name: String? = null): Builder

150

151

/** Creates a builder for an anonymous class */

152

fun anonymousClassBuilder(): Builder

153

154

/** Creates a builder for an expect class (multiplatform) */

155

@Deprecated("Use classBuilder with KModifier.EXPECT instead")

156

fun expectClassBuilder(name: String): Builder

157

fun expectClassBuilder(className: ClassName): Builder

158

159

/** Creates a builder for a fun interface */

160

fun funInterfaceBuilder(name: String): Builder

161

fun funInterfaceBuilder(className: ClassName): Builder

162

163

/** Creates a builder for a value class */

164

@Deprecated("Use classBuilder with KModifier.VALUE instead")

165

fun valueClassBuilder(name: String): Builder

166

fun valueClassBuilder(className: ClassName): Builder

167

}

168

169

/** Builder for constructing TypeSpec instances */

170

class Builder {

171

/** Adds modifiers to the type */

172

fun addModifiers(vararg modifiers: KModifier): Builder

173

fun addModifiers(modifiers: Iterable<KModifier>): Builder

174

175

/** Adds type parameters (generics) */

176

fun addTypeVariable(typeVariable: TypeVariableName): Builder

177

fun addTypeVariables(typeVariables: Iterable<TypeVariableName>): Builder

178

179

/** Sets the superclass */

180

fun superclass(superclass: TypeName): Builder

181

fun superclass(superclass: KClass<*>): Builder

182

183

/** Adds superinterfaces */

184

fun addSuperinterface(superinterface: TypeName): Builder

185

fun addSuperinterface(superinterface: KClass<*>): Builder

186

fun addSuperinterface(superinterface: TypeName, delegate: CodeBlock): Builder

187

188

/** Adds enum constants (for enum classes) */

189

fun addEnumConstant(name: String): Builder

190

fun addEnumConstant(name: String, typeSpec: TypeSpec): Builder

191

192

/** Adds properties to the type */

193

fun addProperty(propertySpec: PropertySpec): Builder

194

fun addProperties(propertySpecs: Iterable<PropertySpec>): Builder

195

196

/** Adds functions to the type */

197

fun addFunction(funSpec: FunSpec): Builder

198

fun addFunctions(funSpecs: Iterable<FunSpec>): Builder

199

200

/** Adds nested types */

201

fun addType(typeSpec: TypeSpec): Builder

202

fun addTypes(typeSpecs: Iterable<TypeSpec>): Builder

203

204

/** Adds init blocks */

205

fun addInitializerBlock(block: CodeBlock): Builder

206

207

/** Adds annotations */

208

fun addAnnotation(annotationSpec: AnnotationSpec): Builder

209

fun addAnnotation(annotation: ClassName): Builder

210

fun addAnnotation(annotation: Class<*>): Builder

211

fun addAnnotation(annotation: KClass<*>): Builder

212

213

/** Adds KDoc documentation */

214

fun addKdoc(format: String, vararg args: Any): Builder

215

fun addKdoc(block: CodeBlock): Builder

216

217

/** Adds context receivers */

218

fun contextReceivers(receiverTypes: Iterable<TypeName>): Builder

219

fun contextReceivers(vararg receiverTypes: TypeName): Builder

220

221

/** Sets primary constructor */

222

fun primaryConstructor(primaryConstructor: FunSpec?): Builder

223

224

/** Builds the TypeSpec */

225

fun build(): TypeSpec

226

}

227

}

228

```

229

230

**Usage Examples:**

231

232

```kotlin

233

// Basic class with properties and methods

234

val personClass = TypeSpec.classBuilder("Person")

235

.addModifiers(KModifier.DATA)

236

.primaryConstructor(

237

FunSpec.constructorBuilder()

238

.addParameter("name", String::class)

239

.addParameter("age", Int::class)

240

.build()

241

)

242

.addProperty(PropertySpec.builder("name", String::class).initializer("name").build())

243

.addProperty(PropertySpec.builder("age", Int::class).initializer("age").build())

244

.addFunction(

245

FunSpec.builder("greet")

246

.returns(String::class)

247

.addStatement("return %S + name", "Hello, my name is ")

248

.build()

249

)

250

.build()

251

252

// Generic interface

253

val repositoryInterface = TypeSpec.interfaceBuilder("Repository")

254

.addTypeVariable(TypeVariableName("T"))

255

.addFunction(

256

FunSpec.builder("save")

257

.addModifiers(KModifier.ABSTRACT)

258

.addParameter("entity", TypeVariableName("T"))

259

.build()

260

)

261

.addFunction(

262

FunSpec.builder("findById")

263

.addModifiers(KModifier.ABSTRACT)

264

.addParameter("id", Long::class)

265

.returns(TypeVariableName("T").copy(nullable = true))

266

.build()

267

)

268

.build()

269

270

// Enum class

271

val statusEnum = TypeSpec.enumBuilder("Status")

272

.addEnumConstant("PENDING")

273

.addEnumConstant("APPROVED")

274

.addEnumConstant("REJECTED")

275

.addProperty(

276

PropertySpec.builder("displayName", String::class)

277

.initializer("displayName")

278

.build()

279

)

280

.primaryConstructor(

281

FunSpec.constructorBuilder()

282

.addParameter("displayName", String::class)

283

.build()

284

)

285

.build()

286

287

// Sealed class hierarchy

288

val resultSealed = TypeSpec.classBuilder("Result")

289

.addModifiers(KModifier.SEALED)

290

.addTypeVariable(TypeVariableName("T"))

291

.addType(

292

TypeSpec.classBuilder("Success")

293

.addModifiers(KModifier.DATA)

294

.addTypeVariable(TypeVariableName("T"))

295

.superclass(ClassName("", "Result").parameterizedBy(TypeVariableName("T")))

296

.primaryConstructor(

297

FunSpec.constructorBuilder()

298

.addParameter("value", TypeVariableName("T"))

299

.build()

300

)

301

.addProperty(

302

PropertySpec.builder("value", TypeVariableName("T"))

303

.initializer("value")

304

.build()

305

)

306

.build()

307

)

308

.addType(

309

TypeSpec.classBuilder("Error")

310

.addModifiers(KModifier.DATA)

311

.addTypeVariable(TypeVariableName("T"))

312

.superclass(ClassName("", "Result").parameterizedBy(TypeVariableName("T")))

313

.primaryConstructor(

314

FunSpec.constructorBuilder()

315

.addParameter("message", String::class)

316

.build()

317

)

318

.addProperty(

319

PropertySpec.builder("message", String::class)

320

.initializer("message")

321

.build()

322

)

323

.build()

324

)

325

.build()

326

```

327

328

### Object and Companion Object Specification

329

330

Creates object declarations and companion objects with full support for properties, functions, and initialization.

331

332

```kotlin { .api }

333

// Object declaration examples using TypeSpec.objectBuilder()

334

// Companion object examples using TypeSpec.companionObjectBuilder()

335

```

336

337

**Usage Examples:**

338

339

```kotlin

340

// Singleton object

341

val configObject = TypeSpec.objectBuilder("AppConfig")

342

.addProperty(

343

PropertySpec.builder("API_URL", String::class)

344

.addModifiers(KModifier.CONST)

345

.initializer("%S", "https://api.example.com")

346

.build()

347

)

348

.addFunction(

349

FunSpec.builder("initialize")

350

.addStatement("println(%S)", "Initializing app configuration")

351

.build()

352

)

353

.build()

354

355

// Class with companion object

356

val utilityClass = TypeSpec.classBuilder("MathUtils")

357

.addType(

358

TypeSpec.companionObjectBuilder()

359

.addFunction(

360

FunSpec.builder("max")

361

.addParameter("a", Int::class)

362

.addParameter("b", Int::class)

363

.returns(Int::class)

364

.addStatement("return if (a > b) a else b")

365

.build()

366

)

367

.build()

368

)

369

.build()

370

```