I am currently refactoring some Kotlin code - I have a nice solution to a simple refactor but unsure of how to do this within the Koltin syntax using maps. Any help would be great!
Current code
here are my data classes:
public sealed class DocumentBody {
public data class Information(
val Id: String,
val name: String,
val sort: Int = 2
) : DocumentBody ()
public data class Location(
val name: String,
val address: String? = null,
val sort: Int = 3
) : DocumentBody()
public data class Rating(
val name: String,
val rating: Int,
val sort: Int = 3
) : DocumentBody()
}
Currently within my code base there is a extension function where it gets some extended info based upon type of context this is:
private fun DocumentBody.getExtendedInfo(
settings: Settings = Settings()
): String? {
return if (settings.versions != null) {
when (this) {
is DocumentBody.Information ->
getExtentedInfo(ContentType.Information, settings.versions)
is DocumentBody.Location ->
getExtentedInfo(ContentType.Location, settings.versions)
is DocumentBody.Rating ->
getExtentedInfo(ContentType.Rating, settings.versions)
}
} else {
when (this) {
is DocumentBody.Information ->
ExtentedInfo[ContentType.Information]
is DocumentBody.Location ->
ExtentedInfo[ContentType.Location]
is DocumentBody.Rating ->
ExtentedInfo[ContentType.Rating]
}
}
Refactoring code
when looking into a nicer way to do this I have created a map for the DocumentBody type to ContextType like so (cannot set a type within the map for this - this may be the issue but unsure):
public val getContentTypeFromDocumentBody: Map<Any, ContentType> = mapOf(
DocumentBody.Information to ContentType.Information,
DocumentBody.Location to ContentType.Location,
DocumentBody.Rating to ContentType.Rating
)
here then I want to be able to call this and get the ContentType from the key:
getContentTypeFromDocumentBody[docBodyType]
this is currently passing through the data but I want the type. I have explored how to do this with the idea of something like this:
private fun DocumentBody.getExtendedInfo(settings: Settings = Settings()): String {
getContentTypeFromDocumentBody.keys.map { docBodyType ->
when (this) {
is docBodyType -> getContentTypeFromDocumentBody[docBodyType]
else -> error("invalid document type")
}
}
}
but this doesn't work and creat has red lines under docBodyType on the 4th line.
Basically I want to pass in the type of DocumentBody into this new map to get a Content Type, hope this idea of what I am trying to do makes sense. Any help would be great!