Do and of you guys expose array types on propertie...
# codereview
g
Do and of you guys expose array types on properties using kotlins array contravariance as a way to protect from mutation? IE:
class MyImmutableType(val property: Array<out AnotherImmutableType>)
Im guessing that a java caller of the same file is only going to see
AnotherImmutableType[]
So... its not a very strong gaurentee; but if you're pure kotlin... is it strong enough?
c
I don't understand what you are trying to do. Arrays are mutable, a true immutable type can never have a public array property.
g
The 'out' in
Array<out String>
means you cant call set. I'm wondering if anyone uses this as a pseudo immutable type as a result.
c
Oh, you're right, and I don't see any other way to mutate it. It wouldn't work on
List
because of
clear
, but it does seem to work on arrays 🤔 I still would just use a
List
, though. I think the intent is clearer.
👆 1
g
so to bump this, one "trick" is to use
JVMName
to make an accessor inaccessible from java:
Copy code
class Thingy(
  private val dogs: Array<out Dog>
){
  @JvmName("\$accessDogs") fun accessDogs() = dogs
}
this will mean java callers cannot call
accessDogs
as they cant denote the function name, but kotlin will have no trouble... though I'm guessing the kotlin source code name thus gets embedded as an annotation on the result?