unmodifiableList had small but noticeable performance impact last time I checked. Kotlin lists save some trouble here since they just hide mutation methods in design-time without affecting runtime, but it works fine until you actually want to change something like in the example above. For now, one needs to just think in advance about where to use reference and where clone constructor.
To do so, requires using sun.misc.Unsafe. While it is sometimes necessary to use this, it is unsafe (if it breaks you get to keep the pieces). That means that the burden of correctness is on the user of unsafe, not on the implementer of the object that would be safe in it’s absense. One caveat here is Serializable that needs special handling (btw. custom libraries such as Kryo use Unsafe so need to be used with care)
Are you sure?
class Test() {
var a: Int = 5
private set
}
fun main(vararg args: String){
val t = Test()
val field = Test::class.declaredMemberProperties.find { it.name == "a" }!!.javaField!!
field.isAccessible = true
println(field.get(t))
field.set(t, 4)
println(t.a)
}
This works fine for me.
Just pointing out that this can be disabled using the security manager, but by default it is allowed.
1 Like