diff --git a/ion-schema/src/main/kotlin/com/amazon/ionschema/internal/SchemaImpl_2_0.kt b/ion-schema/src/main/kotlin/com/amazon/ionschema/internal/SchemaImpl_2_0.kt index 24663add..11567001 100644 --- a/ion-schema/src/main/kotlin/com/amazon/ionschema/internal/SchemaImpl_2_0.kt +++ b/ion-schema/src/main/kotlin/com/amazon/ionschema/internal/SchemaImpl_2_0.kt @@ -327,14 +327,15 @@ internal class SchemaImpl_2_0 internal constructor( val newIsl = mutableListOf() var newTypeAdded = false - isl.forEachIndexed { idx, value -> + isl.forEach { value -> if (!newTypeAdded) { if (isType(value) && (value["name"] as? IonSymbol)?.stringValue() == type.name) { // new type replaces existing type of the same name newIsl.add(type.isl.clone()) newTypeAdded = true - return@forEachIndexed - } else if (value.hasTypeAnnotation("schema_footer") || idx == isl.lastIndex) { + return@forEach + } else if (value.hasTypeAnnotation("schema_footer")) { + // Insert the new type right before the footer newIsl.add(type.isl.clone()) newTypeAdded = true } diff --git a/ion-schema/src/test/kotlin/com/amazon/ionschema/internal/SchemaImpl_2_0_Test.kt b/ion-schema/src/test/kotlin/com/amazon/ionschema/internal/SchemaImpl_2_0_Test.kt index 34c159c1..5e32740d 100644 --- a/ion-schema/src/test/kotlin/com/amazon/ionschema/internal/SchemaImpl_2_0_Test.kt +++ b/ion-schema/src/test/kotlin/com/amazon/ionschema/internal/SchemaImpl_2_0_Test.kt @@ -65,6 +65,20 @@ class SchemaImpl_2_0_Test { assertEquals(expectedNewFooTypeIsl, newFooTypeIsl) } + @Test + fun `plusType(type) should work even when the original schema has only a version marker`() { + val schema = ISS.newSchema("\$ion_schema_2_0") + val newType = schema.newType("type::{ name: bar }") + val newSchema = schema.plusType(newType) + + val oldSchemaTypes = schema.getDeclaredTypes().asSequence().map { it.name }.toSet() + assertEquals(emptySet(), oldSchemaTypes, "The original schema should not be modified.") + + val newSchemaTypes = newSchema.getDeclaredTypes().asSequence().map { it.name }.toSet() + val expectedNewSchemaTypes = setOf("bar") + assertEquals(expectedNewSchemaTypes, newSchemaTypes) + } + @Test fun `getType(name) should return a declared type`() { val schema = ISS.newSchema("\$ion_schema_2_0 type::{ name: foo }")