# How do you namespace things in Kotlin?

**URL:** <https://discuss.kotlinlang.org/t/how-do-you-namespace-things-in-kotlin/21297>\
**Category:** Language Design\
**Created:** [March 22, 2021, 10:36pm UTC](https://discuss.kotlinlang.org/t/how-do-you-namespace-things-in-kotlin/21297 "2021-03-22T22:36:09Z")\
**Posts on this page:** 9\
**Page:** 1

<div class="post-metadata">

**Author:** ![oakkitten](https://avatars.discourse-cdn.com/v4/letter/o/7cd45c/32.png) [@oakkitten](https://discuss.kotlinlang.org/u/oakkitten)\
**Post date:** [March 22, 2021, 10:36pm UTC](https://discuss.kotlinlang.org/t/how-do-you-namespace-things-in-kotlin/21297/1 "2021-03-22T22:36:09Z")

</div>

I love Kotlin but I’m not quite sure how to properly separate concepts.

To give concrete examples:

- **Default enum value**

- **Factory methods**

- **Global constants and variables**

- **Nested classes**

* * *

It feels that it would be useful to allow importing packages. This would also help with conflicting import names. For instance, instead of writing

```nohighlight
import library.widget.Preference as WidgetPreferenece
import myapp.config.Preference as ConfigPreference

```

you could write

```nohighlight
import library.widget as widget
import myapp.config as config

val foo = findView<widget.Preference>()
val bar = config.Preference()

```

Also it would perhaps be nice to be able to write `namespace ButtonAnimation {}` or something like the following, that would be used solely for keeping constants, factory methods, etc together:

```nohighlight
enum class Enum {
    Value1,
    Value2;

    companion namespace { // not an object!
        val default = Value2
    }
}

```

---

<div class="post-metadata">

**Author:** ![TrevorHackman](https://avatars.discourse-cdn.com/v4/letter/t/f05b48/32.png) [@TrevorHackman](https://discuss.kotlinlang.org/u/TrevorHackman)\
**Post date:** [March 22, 2021, 11:43pm UTC](https://discuss.kotlinlang.org/t/how-do-you-namespace-things-in-kotlin/21297/2 "2021-03-22T23:43:11Z")

</div>

Always using top-level is a terrible alternative to using object for namespaces imo. If you have a large amount of top-level items things can get out of hand. Using objects for namespaces gives you structure.

It is a sore spot in Kotlin. There should be a namespace keyword, but in the mean time I would use the object keyword. Unless you’re using object to make thousands upon thousands of namespaces, the overhead from all the unnecessary objects being created is negligible.

But rather than a namespace keyword, if this is possible, it would be nice if the compiler could detect that your object is only being used as a namespace and not generate unnecessary objects under the hood.

---

<div class="post-metadata">

**Author:** ![wyaeld](https://avatars.discourse-cdn.com/v4/letter/w/ad7895/32.png) [@wyaeld](https://discuss.kotlinlang.org/u/wyaeld)\
**Post date:** [March 26, 2021, 2:58am UTC](https://discuss.kotlinlang.org/t/how-do-you-namespace-things-in-kotlin/21297/3 "2021-03-26T02:58:24Z")

</div>

I’ve never found using objects for namespaces to create a problem. We use it quite heavily for typesafe dependency management.

I do think that the awkward the Op is seeing above is because of an unintentional misuse of the Enum itself. The Enum class is for detailing all possible values, things like default values are context-specific business logic in many systems, so for that reason we wouldn’t allow the above.

I recommend keeping business logic in specialised service classes, which aids testability.  
Alternatively in Kotlin I believe you could look at using an Interface to declare a default enum

---

<div class="post-metadata">

**Author:** ![oakkitten](https://avatars.discourse-cdn.com/v4/letter/o/7cd45c/32.png) [@oakkitten](https://discuss.kotlinlang.org/u/oakkitten)\
**Post date:** [March 27, 2021, 11:29pm UTC](https://discuss.kotlinlang.org/t/how-do-you-namespace-things-in-kotlin/21297/4 "2021-03-27T23:29:14Z")

</div>

> unintentional misuse of the Enum itself

That depends on the Enum in question imo. I use Enums a lot for stuff like preference files or network protocols so I also keep factory methods inside them (e.g. `Compression.fromString("zlib") ` → `Compression.Zlib`) and so default values go there as well. Perhaps you can argue that this stuff should be elsewhere but I find this kind of organization much easier to read

---

<div class="post-metadata">

**Author:** ![benwoodworth](https://avatars.discourse-cdn.com/v4/letter/b/ad7895/32.png) [@benwoodworth](https://discuss.kotlinlang.org/u/benwoodworth)\
**Post date:** [March 28, 2021, 4:01am UTC](https://discuss.kotlinlang.org/t/how-do-you-namespace-things-in-kotlin/21297/5 "2021-03-28T04:01:16Z")

</div>

The possibility of adding a namespace keyword _is_ on the radar:

[![](https://us1.discourse-cdn.com/flex019/uploads/kotlinlang/original/2X/b/bfaf1ff1f24f2b28b5d00a935ff4ab5083b86679.jpeg "A Look Into the Future by Roman Elizarov") ](https://www.youtube.com/watch?v=0FF19HJDqMo)

---

<div class="post-metadata">

**Author:** ![wyaeld](https://avatars.discourse-cdn.com/v4/letter/w/ad7895/32.png) [@wyaeld](https://discuss.kotlinlang.org/u/wyaeld)\
**Post date:** [March 28, 2021, 7:30pm UTC](https://discuss.kotlinlang.org/t/how-do-you-namespace-things-in-kotlin/21297/6 "2021-03-28T19:30:47Z")

</div>

If you have a look at the literature for the design of enums, in various languages, you’ll find clear patterns.  
Nowhere in the Java documentation, or the Kotlin documentation, will you find examples of them being used for business logic like default values.

You can do it, but its not considered a good idea.

If using for any sort of configuration, when writing larger systems in Kotlin, I recommend adopting “DomainPreferences” classes, eg “EmailPreferences” to wrap groups of values, since they keep things like defaults and such in a single place, and they make it easy to test dependant services, since you can just feed them a POJO - what do we call POJOs in Kotlin anyway…?

---

<div class="post-metadata">

**Author:** ![oakkitten](https://avatars.discourse-cdn.com/v4/letter/o/7cd45c/32.png) [@oakkitten](https://discuss.kotlinlang.org/u/oakkitten)\
**Post date:** [March 28, 2021, 10:10pm UTC](https://discuss.kotlinlang.org/t/how-do-you-namespace-things-in-kotlin/21297/7 "2021-03-28T22:10:53Z")

</div>

@benwoodworth ah this would be great!

@wyaeld (This is a bit off-topic imo but–)

Here’s a more or less real class that’s a part of a handhshake code

```kt
enum class Compression(val string: String) {
    Off("off"),
    Zlib("zlib");

    companion object {
        val default = Off

        fun fromString(string: String) = Compression::string.find(string)
                ?: throw IllegalArgumentException("Bad compression method: '$string'")
    }
}

```

In my opinion it clearly describes the possible values, the possible string representation of those, what to do when the representation is missing and the way to convert it to a value.

If I have `EmailPreferences` then where do I put the default value for compression? Something like this?

```kt
object EmailPreferences {
    enum class Compression { ... }

    val defaultCompression = ...

    fun compressionFromString(...) = ...
}

```

Or something like this?

```kt
object EmailPreferences {
    object Compression {
        enum class Compression { ... }

        val default = ...

        fun fromString(...) = ...
    }
}

```

I find both of these awful

> Nowhere in the Java documentation, or the Kotlin documentation, will you find examples of them being used for business logic like default values.

I don’t think I’ve seen examples of this in there but then I haven’t seen it elsewhere in the documentation either

---

<div class="post-metadata">

**Author:** ![wyaeld](https://avatars.discourse-cdn.com/v4/letter/w/ad7895/32.png) [@wyaeld](https://discuss.kotlinlang.org/u/wyaeld)\
**Post date:** [March 28, 2021, 11:26pm UTC](https://discuss.kotlinlang.org/t/how-do-you-namespace-things-in-kotlin/21297/8 "2021-03-28T23:26:23Z")

</div>

I’ve put together a very contrived example, but its more to do with the fact that things like ‘defaults’ for use by a system, are often derived from something else.

[https://gist.github.com/wyaeld/27eac0628c67528ac88d1b4437628e40](https://gist.github.com/wyaeld/27eac0628c67528ac88d1b4437628e40)

Depending on the frameworks, some of that info isn’t available until runtime, hence avoiding Objects. We build a lot of microservices on Ktor for example, and the Preference classes we build load the overall config, validate or default their particular domains, report any problems, convert values etc.

---

<div class="post-metadata">

**Author:** ![oakkitten](https://avatars.discourse-cdn.com/v4/letter/o/7cd45c/32.png) [@oakkitten](https://discuss.kotlinlang.org/u/oakkitten)\
**Post date:** [March 29, 2021, 12:12am UTC](https://discuss.kotlinlang.org/t/how-do-you-namespace-things-in-kotlin/21297/9 "2021-03-29T00:12:11Z")

</div>

I see your point, but in your example `defaultAlgorithm` is not really “default” in the sense that `CompressionPreferences` can’t provide a non-default algorithm, nor it would make sense for it to provide one. So it should be just `algorithm` and of course you wouldn’t put it inside the enum.

Where you _would_ use `Compression.default` would be something like

```nohighlight
val compressionString = protocolMessage.getString("compression", null)
val compression = if (compressionString == null) {
    Compression.fromString(compressionString) 
} else {
    Compression.default
}

```

Or you could make it private and call `Compression.fromStringOrNull(...)`
