我有一个抽象类,它包含一些默认值,如下
BaseRequest.kt
abstract class BaseRequest {
abstract val route: String
/** Initially, all requests contain the route param, that's why it has to be added for all requests */
val baseMap: Map<String, String> by lazy { mapOf("route" to route) }
abstract fun toMap(): Map<String, String>
}
现在,对于所有子类,我需要任何扩展BaseRequest
类的人来覆盖toMap()
函数,并返回一个在基类中初始化的初始值为route
的映射。
我的意思是,一旦用户覆盖地图并用任何值填充它,我就会在这些值中添加一个默认值。
例如
项目请求.kt
class ItemsRequest: BaseRequest() {
override val route: String = "items"
override fun toMap(): Map<String, String> = mapOf("id" to "7")
}
对于ItemsRequest
类,我需要从toMap()
函数返回的映射来拥有id
和默认的route
,而不必在每个子类中手动添加它。
这可能吗?
我相信您可以简单地将子类想要返回的映射与超类的baseMap
变量组合起来。既然你在评论中说原始的baseMap
可以修改,你可以简单地在baseMap
和你希望你的特定子类返回的任何其他映射之间使用加运算,比如
override fun toMap(): Map<String, String> = baseMap + mapOf("id" to "7")
请注意baseMap
是如何位于加法运算的左侧的。在这种情况下,如果baseMap
和加号操作右侧的映射中都存在任何键,则从toMap
返回的最终映射将仅包含加号操作右侧映射中的值,用于两个映射的公共键。如果您希望baseMap
键值对具有优先权,并且始终从任何子类的toMap
方法返回的任何映射中返回,那么将baseMap
放在加号运算的右侧,如
override fun toMap(): Map<String, String> = mapOf("id" to "7") + baseMap
然而,假设您希望每个子类的toMap
实现至少返回baseMap
,那么对于覆盖此toMap
方法的每个子类,不断地反复写入baseMap + ...
或... + baseMap
可能是非常多余的。因此,我的建议是将父类中的toMap
函数设为非抽象函数,并定义一个不同的抽象函数,仅用于向从父类派生的类返回映射自定义。这就是我的意思,
abstract class BaseRequest {
abstract val route: String
/** Initially, all requests contain the route param, that's why it has to be added for all requests */
val baseMap: Map<String, String> by lazy { mapOf("route" to route) }
abstract fun subMap(): Map<String, String>
// again, up to you with how you want to combine the two maps,
// assuming you are okay with key-value pairs being overwritten by one of the maps,
// the plus operation is fine
fun toMap(): Map<String, String> = baseMap + subMap()
}
class ItemsRequest: BaseRequest() {
override val route: String = "items"
override fun subMap(): Map<String, String> = mapOf("id" to "7")
}
请注意,subMap
函数也可以是一个变量,就像您如何处理route
变量一样。现在,BaseRequest
的每个派生类的toMap
函数将返回baseMap
和subMap()
的组合。