1

I'm converting a C++ project to Kotlin and I don't have any prior experience in Java but knows some level of Kotlin. Could anyone tell is there any way to convert C++ namespace to Kotlin thing ? I think there is no namespace in Kotlin.

Vencat
  • 1,272
  • 11
  • 36
  • This article discusses the topic. https://arturdryomov.dev/posts/namespacing-in-kotlin Unfortunately it doesn't seem like Kotlin supports this yet. – Markymark Oct 07 '20 at 20:26

2 Answers2

4

As Logan's answer says, the closest equivalent to namespaces is packages. The problem is that it isn't at all close.

The first differences that come to mind are:

  1. In C++, you can have

    // code here is outside any namespace
    namespace A {
    // code here is in namespace A
    namespace B {
    // code here is in namespace A::B
    }
    // code here is in namespace A
    }
    

    In Kotlin, all code in a file belongs to the same package declared at the top.

  2. Packages aren't hierarchical:

    Apparent Hierarchies of Packages

    At first, packages appear to be hierarchical, but they are not. For example, the Java API includes a java.awt package, a java.awt.color package, a java.awt.font package, and many others that begin with java.awt. However, the java.awt.color package, the java.awt.font package, and other java.awt.xxxx packages are not included in the java.awt package. The prefix java.awt (the Java Abstract Window Toolkit) is used for a number of related packages to make the relationship evident, but not to show inclusion.

    Namespaces are.

  3. There is no equivalent to anonymous namespace.

Alexey Romanov
  • 167,066
  • 35
  • 309
  • 487
2

The closest equivalent to namespaces is packages. Like C++ namespaces, they allow classes/symbols with the same name to exist in different packages. Kotlin also extends Java's import syntax to allow renaming imports, which allows you to deal with a single file that wants to use two types with the same name from different packages.

Logan Pickup
  • 2,294
  • 2
  • 22
  • 29