Ray Rahke
05/20/2024, 7:30 PMObject.defineProperty(object1, 'property1', {
value: 42
});
Is there any way for me to achieve something similar in Kotlin, regardless of how hacky or unadvised?Joffrey
05/20/2024, 7:31 PMMap<String, Any>
?Ray Rahke
05/20/2024, 7:32 PMclass Foo {
val x = 5
}
fun main() {
val foo = Foo()
defineProperty(foo, 'y', 7)
println(foo.y) // 7!
}
Joffrey
05/20/2024, 7:32 PMRay Rahke
05/20/2024, 7:32 PMRay Rahke
05/20/2024, 7:32 PMRay Rahke
05/20/2024, 7:33 PMRay Rahke
05/20/2024, 7:33 PMJoffrey
05/20/2024, 7:35 PMRay Rahke
05/20/2024, 7:35 PMRay Rahke
05/20/2024, 7:36 PMfun fn(entity: Physics) {
entity.position // OK!
}
fun main() {
object entity : Health, Skills, Magical
fn(entity) // error, lacks Physics component
entity = entity with Physics
fn(entity) // allowed! entity has Physics
entity = entity without Physics // will still keep Health, Skills, Magical
fn(entity) // error! lacks Physics component
}
Ray Rahke
05/20/2024, 7:36 PMwith
and without
is fake syntax i would imagine for adding or stripping interfaces from instacesRay Rahke
05/20/2024, 7:37 PMRay Rahke
05/20/2024, 7:38 PMYoussef Shoaib [MOD]
05/20/2024, 7:45 PMYoussef Shoaib [MOD]
05/20/2024, 7:51 PMYoussef Shoaib [MOD]
05/20/2024, 7:53 PMwithout
would be possible here, but it's worth a try!CLOVIS
06/03/2024, 7:05 PMCoroutineContext
to achieve this.
class Entity {
private val attributes = HashMap<EntityData.Key<*>, *>()
override fun contains(key: EntityData.Key<*>): Boolean =
attributes.containsKey(key)
override fun <T : EntityData> get(key: EntityData.Key<T>): T =
attributes[key]!! as T
override fun <T : EntityData> set(key: EntityData.Key<T>, value: T) =
attributes[key] = value
}
interface EntityData {
interface Key<E : EntityData>
}
class Physics(
…
) : EntityData {
companion object : EntityData.Key<Physics>
}
class Health(
…
) : EntityData {
companion object : EntityData.Key<Health>
}
class Skills(
…
) : EntityData {
companion object : EntityData.Key<Skills>
}
Then, usage:
fun main() {
val entity = Entity()
entity[Health] = Health(…)
entity[Skills] = Skills(…)
entity[Magical] = Magical(…)
if (Physics in entity) fn(entity[Physics])
entity[Physics] = Physics(…)
fn(entity[Physics])
}
CLOVIS
06/03/2024, 7:06 PM