Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ namespace equivalent in Kotlin

Tags:

c++

kotlin

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.

like image 984
Vencat Avatar asked Nov 26 '25 05:11

Vencat


2 Answers

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.

like image 112
Alexey Romanov Avatar answered Nov 27 '25 19:11

Alexey Romanov


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.

like image 36
Logan Pickup Avatar answered Nov 27 '25 20:11

Logan Pickup



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!