writeClassDecode method
void
writeClassDecode(
- KotlinOptions generatorOptions,
- Root root,
- Indent indent,
- Class klass,
- Set<
String> customClassNames, - Set<
String> customEnumNames, { - required String dartPackageName,
override
Writes a single class decode method to indent
.
Implementation
@override
void writeClassDecode(
KotlinOptions generatorOptions,
Root root,
Indent indent,
Class klass,
Set<String> customClassNames,
Set<String> customEnumNames, {
required String dartPackageName,
}) {
final String className = klass.name;
indent.write('companion object ');
indent.addScoped('{', '}', () {
indent.writeln('@Suppress("UNCHECKED_CAST")');
indent.write('fun fromList(list: List<Any?>): $className ');
indent.addScoped('{', '}', () {
enumerate(getFieldsInSerializationOrder(klass),
(int index, final NamedType field) {
final HostDatatype hostDatatype = _getHostDatatype(root, field);
// The StandardMessageCodec can give us [Integer, Long] for
// a Dart 'int'. To keep things simple we just use 64bit
// longs in Pigeon with Kotlin.
final bool isInt = field.type.baseName == 'int';
final String listValue = 'list[$index]';
final String fieldType = _kotlinTypeForDartType(field.type);
if (field.type.isNullable) {
if (!hostDatatype.isBuiltin &&
customClassNames.contains(field.type.baseName)) {
indent.write('val ${field.name}: $fieldType? = ');
indent.add('($listValue as List<Any?>?)?.let ');
indent.addScoped('{', '}', () {
indent.writeln('$fieldType.fromList(it)');
});
} else if (!hostDatatype.isBuiltin &&
customEnumNames.contains(field.type.baseName)) {
indent.write('val ${field.name}: $fieldType? = ');
indent.add('($listValue as Int?)?.let ');
indent.addScoped('{', '}', () {
indent.writeln('$fieldType.ofRaw(it)');
});
} else if (isInt) {
indent.write('val ${field.name} = $listValue');
indent.addln('.let { ${_cast(listValue, type: field.type)} }');
} else {
indent.writeln(
'val ${field.name} = ${_cast(listValue, type: field.type)}');
}
} else {
if (!hostDatatype.isBuiltin &&
customClassNames.contains(field.type.baseName)) {
indent.writeln(
'val ${field.name} = $fieldType.fromList($listValue as List<Any?>)');
} else if (!hostDatatype.isBuiltin &&
customEnumNames.contains(field.type.baseName)) {
indent.writeln(
'val ${field.name} = $fieldType.ofRaw($listValue as Int)!!');
} else if (isInt) {
indent.write('val ${field.name} = $listValue');
indent.addln('.let { ${_cast(listValue, type: field.type)} }');
} else {
indent.writeln(
'val ${field.name} = ${_cast(listValue, type: field.type)}');
}
}
});
indent.write('return $className(');
for (final NamedType field in getFieldsInSerializationOrder(klass)) {
final String comma =
getFieldsInSerializationOrder(klass).last == field ? '' : ', ';
indent.add('${field.name}$comma');
}
indent.addln(')');
});
});
}