Accessors
An accessor is a generated getter and setter for one property. It is plain code, so it works where runtime reflection does not exist.
In the descriptor
reflectWithAccessors
reflect leaves accessors out to keep descriptors small. reflectWithAccessors puts one into every property, reachable by name. A var gets a setter, a val a read-only accessor.
Switch the theme through the accessor
The buttons call set on a Settings instance; the value is read back with get.
- theme.get(settings)
- light
- theme.hasSetter
- true
- version.hasSetter
- false
- reflect[Settings].getPropertyAccessor("theme")
- None
scala
case class Settings(var theme: String, version: Int)
val descriptor = ReflectMacros.reflectWithAccessors[Settings]
val theme = descriptor.requirePropertyAccessor("theme")
val settings = Settings("light", 1)
if theme.hasSetter then theme.set(settings, "dark")
From a selector
makeAccessor
makeAccessor builds one accessor from a selector, without a descriptor around it. The selector is checked by the compiler.
- theme.get(Settings("light", 1))
- light
- theme.hasSetter
- false
scala
val theme = ReflectMacros.makeAccessor[Settings, String](_.theme)
theme.get(settings)
Read-only in 1.1.4
In version 1.1.4 makeAccessor finds no setter, even for a var: its accessor reads, and set throws UnsupportedOperationException. Take the accessor from reflectWithAccessors when you need to write.