类型别名¶
KotlinPoet 提供了用于创建类型别名的 API,支持简单的类名、参数化类型和 Lambda 表达式
val k = TypeVariableName("K")
val t = TypeVariableName("T")
val fileTable = Map::class.asClassName()
.parameterizedBy(k, Set::class.parameterizedBy(File::class))
val predicate = LambdaTypeName.get(
parameters = arrayOf(t),
returnType = Boolean::class.asClassName()
)
val helloWorld = FileSpec.builder("com.example", "HelloWorld")
.addTypeAlias(TypeAliasSpec.builder("Word", String::class).build())
.addTypeAlias(
TypeAliasSpec.builder("FileTable", fileTable)
.addTypeVariable(k)
.build()
)
.addTypeAlias(
TypeAliasSpec.builder("Predicate", predicate)
.addTypeVariable(t)
.build()
)
.build()
生成以下内容
package com.example
import java.io.File
import kotlin.Boolean
import kotlin.String
import kotlin.collections.Map
import kotlin.collections.Set
typealias Word = String
typealias FileTable<K> = Map<K, Set<File>>
typealias Predicate<T> = (T) -> Boolean