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

type-system.mddocs/

0

# Type System

1

2

Complete representation of Kotlin's type system including classes, generics, wildcards, lambda types, and type variables. Provides type-safe APIs for working with complex type hierarchies and generic type parameters.

3

4

## Capabilities

5

6

### Base Type Representation

7

8

The foundation of KotlinPoet's type system providing nullability and annotation support for all type representations.

9

10

```kotlin { .api }

11

/**

12

* Base class for all type representations in KotlinPoet

13

*/

14

abstract class TypeName {

15

/** Whether this type is nullable */

16

val isNullable: Boolean

17

18

/** Annotations applied to this type */

19

val annotations: List<AnnotationSpec>

20

21

/** Creates a copy of this type with modified nullability and annotations */

22

fun copy(nullable: Boolean = this.isNullable, annotations: List<AnnotationSpec> = this.annotations): TypeName

23

24

companion object {

25

/** Gets the TypeName for a KClass */

26

fun get(type: KClass<*>): TypeName

27

28

/** Gets the TypeName for a Java Class */

29

fun get(type: Type): TypeName

30

31

/** Gets the TypeName for a Java Class with variance */

32

fun get(type: Type, map: Map<TypeVariable<*>, TypeName>): TypeName

33

}

34

}

35

```

36

37

### Class and Interface Types

38

39

Represents references to classes, interfaces, and objects with full package qualification and parameterization support.

40

41

```kotlin { .api }

42

/**

43

* Type name for classes, interfaces, and objects

44

*/

45

class ClassName : TypeName {

46

/** The package name containing this class */

47

val packageName: String

48

49

/** The simple name of this class */

50

val simpleName: String

51

52

/** Nested class names if this represents a nested class */

53

val simpleNames: List<String>

54

55

/** The enclosing class if this is a nested class */

56

val enclosingClassName: ClassName?

57

58

/** Creates a nested class name within this class */

59

fun nestedClass(simpleName: String): ClassName

60

61

/** Creates a sibling class name in the same package */

62

fun peerClass(simpleName: String): ClassName

63

64

/** Creates a parameterized type using this class as the raw type */

65

fun parameterizedBy(vararg typeArguments: TypeName): ParameterizedTypeName

66

fun parameterizedBy(typeArguments: Iterable<TypeName>): ParameterizedTypeName

67

68

companion object {

69

/** Creates a ClassName from package and simple names */

70

fun get(packageName: String, simpleName: String, vararg simpleNames: String): ClassName

71

72

/** Creates a ClassName from a KClass */

73

fun get(klass: KClass<*>): ClassName

74

75

/** Creates a ClassName from a Java Class */

76

fun get(clazz: Class<*>): ClassName

77

78

/** Attempts to create a ClassName from a string representation */

79

fun bestGuess(classNameString: String): ClassName

80

}

81

}

82

```

83

84

**Usage Examples:**

85

86

```kotlin

87

import com.squareup.kotlinpoet.*

88

89

// Basic class names

90

val stringClass = ClassName.get("kotlin", "String")

91

val listClass = ClassName.get("kotlin.collections", "List")

92

val mapClass = ClassName.get(Map::class)

93

94

// Nested class names

95

val outerClass = ClassName.get("com.example", "Outer")

96

val innerClass = outerClass.nestedClass("Inner")

97

val siblingClass = outerClass.peerClass("Sibling")

98

99

// From string guessing

100

val guessedClass = ClassName.bestGuess("java.util.concurrent.ConcurrentHashMap")

101

102

// Creating parameterized types

103

val stringList = listClass.parameterizedBy(STRING)

104

val stringIntMap = mapClass.parameterizedBy(STRING, INT)

105

106

// Custom classes for domain modeling

107

val userClass = ClassName.get("com.example.model", "User")

108

val repositoryClass = ClassName.get("com.example.repository", "UserRepository")

109

```

110

111

### Parameterized (Generic) Types

112

113

Represents generic types with type arguments, supporting complex nested generics and variance.

114

115

```kotlin { .api }

116

/**

117

* Type name for parameterized types (generics like List<String>)

118

*/

119

class ParameterizedTypeName : TypeName {

120

/** The raw type without type parameters */

121

val rawType: ClassName

122

123

/** The type arguments for this parameterized type */

124

val typeArguments: List<TypeName>

125

126

companion object {

127

/** Creates a parameterized type from a raw type and type arguments */

128

fun get(rawType: ClassName, vararg typeArguments: TypeName): ParameterizedTypeName

129

fun get(rawType: ClassName, typeArguments: List<TypeName>): ParameterizedTypeName

130

}

131

}

132

```

133

134

**Usage Examples:**

135

136

```kotlin

137

// Basic parameterized types

138

val stringList = ParameterizedTypeName.get(LIST, STRING)

139

val intSet = ParameterizedTypeName.get(SET, INT)

140

val stringIntMap = ParameterizedTypeName.get(MAP, STRING, INT)

141

142

// Nested generics

143

val listOfStringLists = ParameterizedTypeName.get(LIST, stringList)

144

val mapOfStringToIntList = ParameterizedTypeName.get(

145

MAP,

146

STRING,

147

ParameterizedTypeName.get(LIST, INT)

148

)

149

150

// Complex generic hierarchies

151

val repositoryType = ParameterizedTypeName.get(

152

ClassName.get("com.example", "Repository"),

153

ClassName.get("com.example.model", "User")

154

)

155

156

// Generic with wildcards

157

val wildcardList = ParameterizedTypeName.get(

158

LIST,

159

WildcardTypeName.producerOf(ClassName.get("", "Number"))

160

)

161

```

162

163

### Type Variables

164

165

Represents type parameters in generic declarations (T, E, K, V, etc.) with optional bounds.

166

167

```kotlin { .api }

168

/**

169

* Type name for type variables (generic type parameters like T, E, etc.)

170

*/

171

class TypeVariableName : TypeName {

172

/** The name of the type variable */

173

val name: String

174

175

/** Upper bounds for this type variable */

176

val bounds: List<TypeName>

177

178

/** Variance of this type variable (in, out, or invariant) */

179

val variance: KModifier?

180

181

/** Whether this type variable is reified */

182

val isReified: Boolean

183

184

companion object {

185

/** Creates a type variable with the given name */

186

fun get(name: String): TypeVariableName

187

188

/** Creates a bounded type variable */

189

fun get(name: String, vararg bounds: TypeName): TypeVariableName

190

fun get(name: String, bounds: List<TypeName>): TypeVariableName

191

192

/** Creates a type variable from a Java TypeVariable */

193

fun get(typeVariable: java.lang.reflect.TypeVariable<*>): TypeVariableName

194

fun get(typeVariable: java.lang.reflect.TypeVariable<*>, map: Map<java.lang.reflect.TypeVariable<*>, TypeName>): TypeVariableName

195

}

196

}

197

```

198

199

**Usage Examples:**

200

201

```kotlin

202

// Simple type variables

203

val tVar = TypeVariableName.get("T")

204

val eVar = TypeVariableName.get("E")

205

val kVar = TypeVariableName.get("K")

206

val vVar = TypeVariableName.get("V")

207

208

// Bounded type variables

209

val numberVar = TypeVariableName.get("T", NUMBER)

210

val comparableVar = TypeVariableName.get("T", COMPARABLE.parameterizedBy(TypeVariableName.get("T")))

211

212

// Multiple bounds

213

val serializableComparableVar = TypeVariableName.get(

214

"T",

215

ClassName.get("java.io", "Serializable"),

216

COMPARABLE.parameterizedBy(TypeVariableName.get("T"))

217

)

218

219

// Reified type variables (for inline functions)

220

val reifiedVar = TypeVariableName.get("T").copy(reified = true)

221

222

// Variance annotations

223

val covariantVar = TypeVariableName.get("T").copy(variance = KModifier.OUT)

224

val contravariantVar = TypeVariableName.get("T").copy(variance = KModifier.IN)

225

226

// Using in generic function

227

val genericFunction = FunSpec.builder("process")

228

.addTypeVariable(TypeVariableName.get("T", ClassName.get("", "Processable")))

229

.addParameter("item", TypeVariableName.get("T"))

230

.returns(TypeVariableName.get("T"))

231

.addStatement("return item.process()")

232

.build()

233

```

234

235

### Wildcard Types

236

237

Represents wildcard types with variance (*, out T, in T) for use-site variance in generic types.

238

239

```kotlin { .api }

240

/**

241

* Type name for wildcard types (*, out Type, in Type)

242

*/

243

class WildcardTypeName : TypeName {

244

/** Upper bounds for this wildcard */

245

val upperBounds: List<TypeName>

246

247

/** Lower bounds for this wildcard */

248

val lowerBounds: List<TypeName>

249

250

companion object {

251

/** Creates a producer wildcard (out Type) */

252

fun producerOf(upperBound: TypeName): WildcardTypeName

253

254

/** Creates a consumer wildcard (in Type) */

255

fun consumerOf(lowerBound: TypeName): WildcardTypeName

256

257

/** Creates an unbounded wildcard (*) */

258

fun subtypeOf(upperBound: TypeName): WildcardTypeName

259

fun supertypeOf(lowerBound: TypeName): WildcardTypeName

260

}

261

}

262

```

263

264

**Usage Examples:**

265

266

```kotlin

267

// Producer wildcards (covariant - out)

268

val producerOfNumber = WildcardTypeName.producerOf(NUMBER)

269

val listOfProducerNumber = LIST.parameterizedBy(producerOfNumber)

270

271

// Consumer wildcards (contravariant - in)

272

val consumerOfString = WildcardTypeName.consumerOf(STRING)

273

val comparatorOfConsumerString = ClassName.get("java.util", "Comparator").parameterizedBy(consumerOfString)

274

275

// Unbounded wildcards

276

val unboundedList = LIST.parameterizedBy(WildcardTypeName.subtypeOf(ANY))

277

278

// Complex variance scenarios

279

val complexWildcard = ParameterizedTypeName.get(

280

MAP,

281

STRING,

282

WildcardTypeName.producerOf(ClassName.get("", "Value"))

283

)

284

```

285

286

### Lambda and Function Types

287

288

Represents function types and lambda expressions with support for receivers, suspending functions, and parameter specifications.

289

290

```kotlin { .api }

291

/**

292

* Type name for function/lambda types like (String, Int) -> Boolean

293

*/

294

class LambdaTypeName : TypeName {

295

/** The receiver type for extension lambdas */

296

val receiver: TypeName?

297

298

/** Parameter specifications for the lambda */

299

val parameters: List<ParameterSpec>

300

301

/** Return type of the lambda */

302

val returnType: TypeName

303

304

/** Whether this is a suspending function type */

305

val isSuspending: Boolean

306

307

companion object {

308

/** Creates a lambda type with the given parameters and return type */

309

fun get(

310

receiver: TypeName? = null,

311

parameters: List<ParameterSpec> = emptyList(),

312

returnType: TypeName

313

): LambdaTypeName

314

315

/** Creates a lambda type with unnamed parameters */

316

fun get(

317

receiver: TypeName? = null,

318

vararg parameters: TypeName,

319

returnType: TypeName

320

): LambdaTypeName

321

}

322

}

323

```

324

325

**Usage Examples:**

326

327

```kotlin

328

// Simple function types

329

val stringToInt = LambdaTypeName.get(returnType = INT, parameters = *arrayOf(STRING))

330

val binaryIntOperation = LambdaTypeName.get(returnType = INT, parameters = *arrayOf(INT, INT))

331

332

// Function type with no parameters

333

val supplier = LambdaTypeName.get(returnType = STRING)

334

335

// Function type with named parameters

336

val namedParamFunction = LambdaTypeName.get(

337

parameters = listOf(

338

ParameterSpec.builder("name", STRING).build(),

339

ParameterSpec.builder("age", INT).build()

340

),

341

returnType = STRING

342

)

343

344

// Extension function type (with receiver)

345

val stringExtension = LambdaTypeName.get(

346

receiver = STRING,

347

returnType = BOOLEAN

348

)

349

350

// Suspending function type

351

val suspendingFunction = LambdaTypeName.get(

352

parameters = listOf(ParameterSpec.unnamed(STRING)),

353

returnType = STRING,

354

isSuspending = true

355

)

356

357

// Higher-order function parameter

358

val higherOrderFunction = FunSpec.builder("processAsync")

359

.addParameter(

360

"callback",

361

LambdaTypeName.get(

362

parameters = listOf(ParameterSpec.unnamed(STRING)),

363

returnType = UNIT,

364

isSuspending = true

365

)

366

)

367

.build()

368

369

// Complex function type with multiple parameters

370

val complexCallback = LambdaTypeName.get(

371

parameters = listOf(

372

ParameterSpec.builder("success", BOOLEAN).build(),

373

ParameterSpec.builder("data", STRING.copy(nullable = true)).build(),

374

ParameterSpec.builder("error", ClassName.get("", "Exception").copy(nullable = true)).build()

375

),

376

returnType = UNIT

377

)

378

```

379

380

### Dynamic Type

381

382

Represents Kotlin's dynamic type for JavaScript interoperability.

383

384

```kotlin { .api }

385

/**

386

* Represents Kotlin's dynamic type

387

*/

388

object Dynamic : TypeName

389

```

390

391

**Usage Examples:**

392

393

```kotlin

394

// Dynamic type for JavaScript interop

395

val dynamicProperty = PropertySpec.builder("jsObject", Dynamic)

396

.initializer("js(%S)", "{}")

397

.build()

398

399

val dynamicFunction = FunSpec.builder("callJsFunction")

400

.addParameter("obj", Dynamic)

401

.addParameter("method", STRING)

402

.returns(Dynamic)

403

.addStatement("return obj[method]()")

404

.build()

405

```

406

407

## Built-in Type Constants

408

409

KotlinPoet provides convenient constants for common Kotlin types:

410

411

```kotlin { .api }

412

// Primitive types

413

val UNIT: ClassName

414

val BOOLEAN: ClassName

415

val BYTE: ClassName

416

val SHORT: ClassName

417

val INT: ClassName

418

val LONG: ClassName

419

val CHAR: ClassName

420

val FLOAT: ClassName

421

val DOUBLE: ClassName

422

val STRING: ClassName

423

424

// Unsigned primitive types

425

val U_BYTE: ClassName

426

val U_SHORT: ClassName

427

val U_INT: ClassName

428

val U_LONG: ClassName

429

430

// Common reference types

431

val ANY: ClassName

432

val NOTHING: ClassName

433

val NUMBER: ClassName

434

val COMPARABLE: ClassName

435

val CHAR_SEQUENCE: ClassName

436

val THROWABLE: ClassName

437

val ANNOTATION: ClassName

438

439

// Collection types

440

val ITERABLE: ClassName

441

val COLLECTION: ClassName

442

val LIST: ClassName

443

val SET: ClassName

444

val MAP: ClassName

445

val MUTABLE_ITERABLE: ClassName

446

val MUTABLE_COLLECTION: ClassName

447

val MUTABLE_LIST: ClassName

448

val MUTABLE_SET: ClassName

449

val MUTABLE_MAP: ClassName

450

451

// Array types

452

val ARRAY: ClassName

453

val BOOLEAN_ARRAY: ClassName

454

val BYTE_ARRAY: ClassName

455

val CHAR_ARRAY: ClassName

456

val SHORT_ARRAY: ClassName

457

val INT_ARRAY: ClassName

458

val LONG_ARRAY: ClassName

459

val FLOAT_ARRAY: ClassName

460

val DOUBLE_ARRAY: ClassName

461

462

// Unsigned array types

463

val U_BYTE_ARRAY: ClassName

464

val U_SHORT_ARRAY: ClassName

465

val U_INT_ARRAY: ClassName

466

val U_LONG_ARRAY: ClassName

467

468

// Additional type constants

469

val STAR: WildcardTypeName // Represents * wildcard

470

val ENUM: ClassName

471

val MAP_ENTRY: ClassName

472

val MUTABLE_MAP_ENTRY: ClassName

473

```

474

475

**Usage Examples:**

476

477

```kotlin

478

// Using built-in type constants

479

val stringList = LIST.parameterizedBy(STRING)

480

val intArray = INT_ARRAY

481

val stringIntMap = MAP.parameterizedBy(STRING, INT)

482

483

// Nullable variants

484

val nullableString = STRING.copy(nullable = true)

485

val nullableInt = INT.copy(nullable = true)

486

487

// Functions using built-in types

488

val utilityFunction = FunSpec.builder("processData")

489

.addParameter("items", LIST.parameterizedBy(STRING))

490

.addParameter("mapper", LambdaTypeName.get(STRING, returnType = INT))

491

.returns(LIST.parameterizedBy(INT))

492

.addStatement("return items.map(mapper)")

493

.build()

494

```