Last active
September 23, 2020 02:39
-
-
Save DevSrSouza/5f2a1dc8f68852c2496f53866210a861 to your computer and use it in GitHub Desktop.
Typed Tuple generator for Kotlin by calling `tuple("Txt", 15)`
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@file:DependsOn("com.squareup:kotlinpoet:1.6.0") | |
import com.squareup.kotlinpoet.* | |
import java.io.File | |
val maxParameterCount = 12 | |
fun typeName(it: Int) = (65 + it).toChar().toString() | |
val tupleClasses = Array(maxParameterCount) { | |
TypeSpec.classBuilder("Tuple${it+1}") | |
.addModifiers(KModifier.DATA) | |
.apply { | |
val genericTypes = Array(it+1) { | |
TypeVariableName(typeName(it)) | |
} | |
for ((index, genericType) in genericTypes.withIndex()) { | |
addTypeVariable(genericType) | |
} | |
primaryConstructor(FunSpec.constructorBuilder() | |
.apply { | |
for (genericType in genericTypes) { | |
addParameter("value${genericType.name}", genericType) | |
} | |
} | |
.build()) | |
for (genericType in genericTypes) { | |
addProperty(PropertySpec.builder("value${genericType.name}", genericType) | |
.initializer("value${genericType.name}") | |
.build()) | |
} | |
} | |
.build() | |
} | |
FileSpec.builder("kotlin.tuple", "tuple") | |
.apply { | |
for(i in 1..maxParameterCount) { | |
val genericTypes = Array(i) { | |
TypeVariableName(typeName(it)) | |
} | |
addFunction(FunSpec.builder("tuple") | |
.addModifiers(KModifier.INLINE) | |
.apply { | |
val parameters = genericTypes.map { | |
val parameterName = "value${it.name}" | |
addTypeVariable(it) | |
addParameter(parameterName, it) | |
parameterName | |
} | |
addStatement("return Tuple${i}(${parameters.joinToString()})") | |
}.build()) | |
} | |
for (clazz in tupleClasses) { | |
addType(clazz) | |
} | |
} | |
.build() | |
.writeTo(File("../src/generated/kotlinpoet/").canonicalFile) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment