# Idiomatic way to expose a property using a more narrow type

**URL:** <https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863>\
**Category:** Uncategorized\
**Created:** [October 4, 2017, 11:47am UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863 "2017-10-04T11:47:48Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![bennyl](https://avatars.discourse-cdn.com/v4/letter/b/d07c76/32.png) [@bennyl](https://discuss.kotlinlang.org/u/bennyl)\
**Post date:** [October 4, 2017, 11:47am UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/1 "2017-10-04T11:47:48Z")

</div>

I know, the title sound complicated let me try to give an example,

In java I could have the following class:

```java

class InJava {
  private HashSet<String> flags = new HashSet<String>();
  public Set<String> getFlags() { return flags; }
  private void useFlags(){
    flags.add("some-flag");
  }
}

```

In the above class I have a single field of type `HashSet` that exposed as a `Set`  
In kotlin, I will have to do something like:

```kotlin
class InKotlin {
  private val _flags = HashSet<String>()
  val flags: Set<String> get() = _flags

  private fun useFlags() {
    _flags += "some-flag"
  }
}

```

Whats bothers me is the `_flags` property - is there a better idiomatic pattern for such cases?

To clarify:  
The idea is that I do not want to reveal unnecessary implementation details to my library users - for he/she it should not be visible that I chose to use HashSet internally - but only Set - this is the pattern that I am trying to find an idiomatic way to do…

In the case of the above example, I also do not want the library user to depend on the fact that currently the set is mutable as this can change in later versions of the library. Therefore, I would like to have a field that is of type HashSet but from outside of the class it is seen as if it is just a Set

---

<div class="post-metadata">

**Author:** ![cmayrh](https://avatars.discourse-cdn.com/v4/letter/c/c89c15/32.png) [@cmayrh](https://discuss.kotlinlang.org/u/cmayrh)\
**Post date:** [October 4, 2017, 1:10pm UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/2 "2017-10-04T13:10:52Z")

</div>

In Java the example actually only works, because a Java Set is mutable and thus has an add method. If you change Set in Kotlin to a MutableSet you can use a simple val similar to Java.

```auto
class InKotlin {
    val flags: MutableSet<String> = HashSet<String>()

    private fun useFlags() {
        flags += "some-flag"
    }
}

```

If you want to expose an immutable set, I think your solution with a backing property is idiomatic, but I’m new to the language.

---

<div class="post-metadata">

**Author:** ![bennyl](https://avatars.discourse-cdn.com/v4/letter/b/d07c76/32.png) [@bennyl](https://discuss.kotlinlang.org/u/bennyl)\
**Post date:** [October 4, 2017, 1:21pm UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/3 "2017-10-04T13:21:22Z")

</div>

@cmayrh,  
Thanks but I think you missed my point, even if java had a class: ImmutableSet that HashSet implements the following example will still work because I am directly accessing the field of the class, which I could not do in kotlin.

```java
class InJava {
  private HashSet<String> flags = new HashSet<String>();
  public ImmutableSet<String> getFlags() { return flags; } //assume that HashSet implements ImmutableSet
  private void useFlags(){
    flags.add("some-flag");
  }
}

```

The idea is that I do not want to reveal unnecessary implementation details to my library users - for he/she it should not be visible that I am chose to use `HashSet` internally but only `Set` - this is the pattern that I am trying to find an idiomatic way to do…

In the case of the above example, I also do not want the library user to depend on the fact that currently the set is mutable as this can change in later versions of the library. Therefore, I would like to have a field that is of type HashSet but from outside of the class it is seen as if it is just a Set

---

<div class="post-metadata">

**Author:** ![madmax1028](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/madmax1028/32/3335_2.png) [@madmax1028](https://discuss.kotlinlang.org/u/madmax1028)\
**Post date:** [October 4, 2017, 2:25pm UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/4 "2017-10-04T14:25:16Z")

</div>

I think you can do that like this:

```auto
class InKotlin {
	private val _flags = HashSet<String>()
	
	val flags: Set<String> get() = _flags // projection to read-only set
	// or:
	val flags2: Set<String> get() = _flags.toSet() // make a copy of internal set
	
	fun useFlags() {
		_flags += "some-flag"
	}
}

```

---

<div class="post-metadata">

**Author:** ![bennyl](https://avatars.discourse-cdn.com/v4/letter/b/d07c76/32.png) [@bennyl](https://discuss.kotlinlang.org/u/bennyl)\
**Post date:** [October 4, 2017, 2:29pm UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/5 "2017-10-04T14:29:15Z")

</div>

@madmax1028,  
Thanks, But as you can see in my question I am trying to avoid the intermediate `_flags` variable as it just adds clutter to the program that would not exists in the java equivalent

---

<div class="post-metadata">

**Author:** ![vbezhenar](https://avatars.discourse-cdn.com/v4/letter/v/35a633/32.png) [@vbezhenar](https://discuss.kotlinlang.org/u/vbezhenar)\
**Post date:** [October 4, 2017, 3:04pm UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/6 "2017-10-04T15:04:25Z")

</div>

I think it is idiomatic. Similar example [here](https://kotlinlang.org/docs/reference/properties.html#backing-properties).

---

<div class="post-metadata">

**Author:** ![mslenc](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/mslenc/32/3861_2.png) [@mslenc](https://discuss.kotlinlang.org/u/mslenc)\
**Post date:** [October 4, 2017, 3:33pm UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/7 "2017-10-04T15:33:51Z")

</div>

You might also do something like this:

```auto
interface ReadOnlyView {
    val flags: Set<String>
}

class MutableImpl : ReadOnlyView {
    override val flags = HashSet<String>()

    fun useFlags() {
        flags += "some-flag"
    }
}

```

Then expose the object as one or the other, as fits each use case…

---

<div class="post-metadata">

**Author:** ![bennyl](https://avatars.discourse-cdn.com/v4/letter/b/d07c76/32.png) [@bennyl](https://discuss.kotlinlang.org/u/bennyl)\
**Post date:** [October 4, 2017, 5:18pm UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/8 "2017-10-04T17:18:48Z")

</div>

@vbezhenar, yes It seems so - too bad, it really seems (to me) like a design flow  
I expected something like:

```kotlin
val flags: HashSet<String> public get: Set<String>

```

which of course does not work…

@mslenc, Thanks, I actually think that this is a valid option for some cases but for others it just replaces one ceremony with another…

---

<div class="post-metadata">

**Author:** ![Mike\_Wilkes](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/mike_wilkes/32/2620_2.png) [@Mike\_Wilkes](https://discuss.kotlinlang.org/u/Mike_Wilkes)\
**Post date:** [October 5, 2017, 11:50am UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/9 "2017-10-05T11:50:56Z")

</div>

Another alternative. Not much different than yours, but only one variable. `flags` has to be `var` so the += will work, which then means one must ‘protect’ the set method.

Not as clean as what you’re looking for, but I suspect this won’t change in Kotlin.

You have a mutable object internally, so somewhere, you have to explicitly protect it from modification.

```
    class InKotlin {
       var flags: Set<String> = HashSet()
       private set(value) = {}
       private fun useFlags() {
           flags += "some-flag"
       }
   }

```

The bytecode produced is very interesting. Using Intellij decompiler, yours results in the following. Note the useFlags method that constructs a new HashSet everytime.

```
public final class InKotlin {
  @NotNull
  private Set flags = (Set)(new HashSet());
  @NotNull
  public final Set getFlags() {
     return this.flags;
  }
  private final void setFlags(Set value) {
     flags = value;
  }
  private final void useFlags() {
     this.setFlags(SetsKt.plus(this.flags, "some-flag"));
  }
}

```

wherease mine produces this. It adds the item, BUT it assigns the string to a variable first. Take your pick.

```
public final class InKotlin2 {
   private final HashSet _flags = new HashSet();
  @NotNull
  public final Set getFlags() {
     return (Set)this._flags;
  }
  private final void useFlags() {
     Collection var1 = (Collection)this._flags;
     String var2 = "some-flag";
     var1.add(var2);
  }
}

```

---

<div class="post-metadata">

**Author:** ![naxymatt](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/naxymatt/32/4184_2.png) [@naxymatt](https://discuss.kotlinlang.org/u/naxymatt)\
**Post date:** [October 6, 2017, 1:30am UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/10 "2017-10-06T01:30:31Z")

</div>

This should also work, though I don’t think its idiomatic:

```
class InKotlin {
    val flags: Set<String> = HashSet()
    private fun useFlags() {
        (flags as MutableSet) += "some-flag"
    }
}

```

That said, I always go with the private backing field named with an underscore, because that matches what I’ve seen in the Kotlin documentation, so it should surprise other people who read my code the least.

It would be nice to have concise idioms for “publicly readable, privately writable” and “publicly immutable, privately mutable”, preferably idioms that can be combined easily. It seems like they are fairly common use-cases.

---

<div class="post-metadata">

**Author:** ![bennyl](https://avatars.discourse-cdn.com/v4/letter/b/d07c76/32.png) [@bennyl](https://discuss.kotlinlang.org/u/bennyl)\
**Post date:** [October 6, 2017, 7:36am UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/11 "2017-10-06T07:36:23Z")

</div>

@Mike_Wilkes, thanks but as you said yourself it creates a new set every time which means that it actually quite dangerous paradigm to use as It not only hurt performance but also can make thread-safe classes not thread-safe anymore e.g.,:

```kotlin
class ThreadSafe {
       private val _flags = ConcurrentHashMap.newKeySet<String>()
       val flags:Set<String> get() = _flags
       fun addFlag(flag: String) {
           _flags += flag
       }
}

class NotThreadSafe {
       var flags:Set<String> = ConcurrentHashMap.newKeySet<String>(); private set
       fun addFlag(flag: String) {
           _flags += flag 
       }
}

```

In the `NotThreadSafe` class two threads can call the `addFlag` method on the same time and the result may be that only one of their flags will be added while in the `ThreadSafe` class this cannot happen…

---

<div class="post-metadata">

**Author:** ![ddimitrov](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/ddimitrov/32/1519_2.png) [@ddimitrov](https://discuss.kotlinlang.org/u/ddimitrov)\
**Post date:** [October 6, 2017, 9:26am UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/12 "2017-10-06T09:26:28Z")

</div>

Please note Kotlin has no notion of fields. There are only properties and property is considered to be an atomic entity, rather than a shortcut for two methods and field. This design allows to express cleanly many use cases without introducing too many concepts.

Property implementation is encapsulated and may be implemented in different ways depending on the runtime target. As such it may or may not have a backing field, but more important is that Kotlin, the language does not have a notion of “fields”. For some targets, it creates automatic properties to expose fields of the host runtime, and can emit fields for specially annotated properties, but these are implementation specifics.

With this in mind, what you are asking boils down to a single property having different types when it is accessed within and outside the object interface. The idiomatic way is to define private property with the desired type and have second public property delegating to it. It is explicit, conceptually simpler, and still more concise than java bean prop.

---

<div class="post-metadata">

**Author:** ![bennyl](https://avatars.discourse-cdn.com/v4/letter/b/d07c76/32.png) [@bennyl](https://discuss.kotlinlang.org/u/bennyl)\
**Post date:** [October 6, 2017, 9:46am UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/13 "2017-10-06T09:46:43Z")

</div>

@ddimitrov, Yes, I am aware of this, I only used the term “fields” in the problem description since I am comparing to the java solution.

But this discussion is not about accessing fields vs. properties but about an idiomatic way to expose minimal implementation details from a class in the form of a property, indeed, as it seems for now - declaring a private “implementation” property and a public “exporting” property which delegates to the “implementation” property is the way to go.

I would like to note though, that in my eyes it misses some of the main ideas of properties and goes back to the ideology of a private field and a getters/setters, think about it, you are following the same ceremony :  
define a private field =\> define a private implementation property  
define a public getter function =\> define a public exporting property  
Only now you have to do some ugly name mangling on the properties…

---

<div class="post-metadata">

**Author:** ![ddimitrov](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/ddimitrov/32/1519_2.png) [@ddimitrov](https://discuss.kotlinlang.org/u/ddimitrov)\
**Post date:** [October 6, 2017, 10:35am UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/14 "2017-10-06T10:35:09Z")

</div>

You may perceive it that way, but I prefer to see it as clearly delineated internal and external interfaces. It is not a pointless ceremony - the internal property has semantics - you may use it to hook delegates, etc.

And it is up to you whether you resort to name mangling or give it a more human sounding name (how about `mutableFlags`?)

---

<div class="post-metadata">

**Author:** ![Mike\_Wilkes](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/mike_wilkes/32/2620_2.png) [@Mike\_Wilkes](https://discuss.kotlinlang.org/u/Mike_Wilkes)\
**Post date:** [October 6, 2017, 11:14am UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/15 "2017-10-06T11:14:38Z")

</div>

I agree thread safety is an issue. Thank you for raising it as I wasn’t considering that.

I think you mis-understood my post, and therefore got your ThreadSafe and NotThreadSafe implementations reversed.

The variation you originally posted is NOT thread safe, as it uses `Sets.plus(_flags, newItem)` and assigns that using a `setFlags` method.

My variation uses `flags.add(newItem)`

Having \_flags as a val, and doing += results in a call to `Sets.plus(_flags, newItem)` whereas defining it as a var, results in usage of `add`.

@ddimitrov Brings up very valid points. If you want to hide internal implementation, then truly hide it, and use descriptive names.

I suspect we’re still thinking too Java here.

---

<div class="post-metadata">

**Author:** ![bennyl](https://avatars.discourse-cdn.com/v4/letter/b/d07c76/32.png) [@bennyl](https://discuss.kotlinlang.org/u/bennyl)\
**Post date:** [October 6, 2017, 11:20am UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/16 "2017-10-06T11:20:54Z")

</div>

@Mike_Wilkes,  
`+=` is not the `plus` method but the `plusAssign` method, the following is the method code (copied from kotlin stdlib):

```kotlin
/**
 * Adds the specified [element] to this mutable collection.
 */
@kotlin.internal.InlineOnly
public inline operator fun <T> MutableCollection<in T>.plusAssign(element: T) {
    this.add(element)
}

```

As can be seen, the method calls the set’s add method, since the set itself is threadsafe, so its add method and therefore the implementation is threadsafe…

---

<div class="post-metadata">

**Author:** ![bennyl](https://avatars.discourse-cdn.com/v4/letter/b/d07c76/32.png) [@bennyl](https://discuss.kotlinlang.org/u/bennyl)\
**Post date:** [October 6, 2017, 11:30am UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/17 "2017-10-06T11:30:56Z")

</div>

@ddimitrov, I guess we will agree to disagree on this one 🙂

In my eyes, kotlin is a pragmatic language and as such it should have simple idiomatic-promoted ways to do pragmatic day-to-day patterns - the implementation/exposing-properties pattern seems to me like a workaround more than a conscious design choice…

To be clear - I am not saying that it is not the idiomatic way (as from the documentation it seems it is) I just saying that In my eyes it could have been more elegant…

---

<div class="post-metadata">

**Author:** ![Mike\_Wilkes](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/mike_wilkes/32/2620_2.png) [@Mike\_Wilkes](https://discuss.kotlinlang.org/u/Mike_Wilkes)\
**Post date:** [October 6, 2017, 11:59am UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/18 "2017-10-06T11:59:26Z")

</div>

Hmmm. My apologies. Looking at bytecode again, it would appear **I** reversed the 2 representations in my post.

Does show the importance of occasionally visiting the Bytecode to see what’s produced, and verify it’s ok for your scenario, and to better understand what the compiler is producing.

---

<div class="post-metadata">

**Author:** ![restjohn](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/restjohn/32/5322_2.png) [@restjohn](https://discuss.kotlinlang.org/u/restjohn)\
**Post date:** [July 11, 2018, 3:11am UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/19 "2018-07-11T03:11:58Z")

</div>

I agree with @bennyl. I figured that the Kotlin compiler, with all of its advanced type inference, would be able to handle a property with an explicit, immutable type declaration, and an internally typed mutable value, or at least be able to override the getter return type explicitly.

Another alternative in the absence of the way that _feels_ right, is to create a private property of the mutable type then a public getX() function returning the private property as the immutable type.

```
private val stuff: MutableStuff

fun getStuff(): ImmutableStuff { return stuff }

```

but then you lose the cleaner property syntax when invoking getStuff().

I searched this issue out because I am developing Android and I want to expose a LiveData property but use MutableLiveData internally to change the value.

---

<div class="post-metadata">

**Author:** ![Wasabi375](https://sea1.discourse-cdn.com/flex019/user_avatar/discuss.kotlinlang.org/wasabi375/32/4741_2.png) [@Wasabi375](https://discuss.kotlinlang.org/u/Wasabi375)\
**Post date:** [July 11, 2018, 3:26am UTC](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863/20 "2018-07-11T03:26:44Z")

</div>

There is a keep about this issue here:

> <https://github.com/Kotlin/KEEP/pull/122>
>
> \[Proposal\](https://github.com/matejdro/KEEP/blob/private\_public\_property\_types/p…roposals/private\_public\_property\_types.md)
> 
> \[Pre-KEEP Discussion\](https://youtrack.jetbrains.com/issue/KT-14663)

[Next page](https://discuss.kotlinlang.org/t/idiomatic-way-to-expose-a-property-using-a-more-narrow-type/4863.md?page=2)
