Singleton implementation for Attributes.EMPTY

This commit is contained in:
Alexander Nozik 2024-03-27 09:45:56 +03:00
parent ac851bea62
commit 48b334a2b6
2 changed files with 12 additions and 4 deletions

View File

@ -30,7 +30,15 @@ public interface Attributes {
override fun hashCode(): Int
public companion object {
public val EMPTY: Attributes = MapAttributes(emptyMap())
public val EMPTY: Attributes = object : Attributes {
override val content: Map<out Attribute<*>, Any?> get() = emptyMap()
override fun toString(): String = "Attributes.EMPTY"
override fun equals(other: Any?): Boolean = (other as? Attributes)?.isEmpty() ?: false
override fun hashCode(): Int = Unit.hashCode()
}
public fun equals(a1: Attributes, a2: Attributes): Boolean =
a1.keys == a2.keys && a1.keys.all { a1[it] == a2[it] }
@ -43,7 +51,7 @@ internal class MapAttributes(override val content: Map<out Attribute<*>, Any?>)
override fun hashCode(): Int = content.hashCode()
}
public fun Attributes.isEmpty(): Boolean = content.isEmpty()
public fun Attributes.isEmpty(): Boolean = keys.isEmpty()
/**
* Get attribute value or default

View File

@ -15,9 +15,9 @@ public class AttributesBuilder<out O> internal constructor() : Attributes {
private val map = mutableMapOf<Attribute<*>, Any?>()
override fun toString(): String = "Attributes(value=${content.entries})"
override fun toString(): String = "Attributes(value=${map.entries})"
override fun equals(other: Any?): Boolean = other is Attributes && Attributes.equals(this, other)
override fun hashCode(): Int = content.hashCode()
override fun hashCode(): Int = map.hashCode()
override val content: Map<out Attribute<*>, Any?> get() = map