%T for Types
Each object oriented programming language allows the usage of types for variables and other structures. In case of code generation the used type is a very important to tell the structure which type at least the variable etc. should have. To enhance the usage of the API DartPoet has built-in support for types. Just use `%T` to reference a type from the JDK or your own type (more information about that later):
val clazz = ClassSpec.builder("TestClass")
.constants(
ConstantPropertySpec.classConst("test", String::class)
.initWith("%C", "Test")
.build()
)
.build()
val dartFile = DartFile.builder("test_class.dart")
.type(clazz)
.build()
dartFile.write(System.out)That generated .dart file is:
class TestClass {
static const String test = 'Test';
}The example used `String::class` as a referenced type. Some given classes from Kotlin are known classes by the API which have a mapping to match the correspond of the definition in Dart.
This doesn't need to be the case that a type is known by the API itself. For this there is a structure called ClassName which allows the usage of types which are not known by the api and sometimes the codebase of your project.
Here is a similar example, but with the usage of an ClassName to a class that doesn't exit (yet):
We adapt our previous example and use a `ClassName` object instead
val testClass: ClassName = ClassName("Test")
val clazz = ClassSpec.builder("TestClass")
.constants(
ConstantPropertySpec.classConst("test", testClass)
.initWith("%T()", testClass)
.build()
)
.build()
val dartFile = DartFile.builder("test_class.dart")
.type(clazz)
.build()
dartFile.write(System.out)And that example generates the following code:
class TestClass {
static const Test test = Test();;
}You see that the `ClassName` object is very important , and you'll need it frequently when you are using the library. This structure also allows the creation of parameterized types, wildcard types and more.
Reminder: Dart and Kotlin are languages which are not interoperable. The usage of types only does a conversion in the background and doesn't make an import for you like KotlinPoet. You need to the import on your own.
Last updated