Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't create private classes with same name in different modules

Official docs on visibility modifiers in Kotlin say that package-level elements marked private are be visible only in the module in which they are declared.

So class A declared in Module1.kt isn't visible in Module2.kt. But if I try to add to Module2.kt it's own class A I get the Redeclaration: A error.

Since I can't access in Module2.kt to Module1's A class, why isn't the name A free to use?

like image 315
netimen Avatar asked Feb 15 '16 12:02

netimen


People also ask

When can two classes have the same name?

Yes, you can have two classes with the same name in multiple packages. However, you can't import both classes in the same file using two import statements. You'll have to fully qualify one of the class names if you really need to reference both of them.

Which concept in Java allows the user to define two classes with same names?

For convenience, Java allows you to write more than one method in the same class definition with the same name. For example, you can have two methods in ShoppingCart class named computeCost. Having two or more methods named the same in the same class is called overloading.

Which are valid visibility modifiers in Kotlin?

There are four visibility modifiers in Kotlin: private , protected , internal , and public .

What is internal class in Kotlin?

Internal is a new modifier available in Kotlin that's not there in Java. Setting a declaration as internal means that it'll be available in the same module only. By module in Kotlin, we mean a group of files that are compiled together. internal class A { } internal val x = 0.


1 Answers

"A module is a set of Kotlin files compiled together" (Visibility Modifiers - Kotlin Programming Language).

In your example, Module1.kt and Module2.kt are separate source files and despite their names they are not necessarily part of separate modules:

  • If they are compiled together then they are part of the same module.
  • If they are compiled separately from one another then they will be part of different modules and each can define their own private class A.

Keep in mind that visibility is different from identity. Even if a class is not visible elsewhere it doesn't mean that it does not exist. Loading multiple class declarations with the same fully-qualified name can (and likely will) cause issues at run-time.

like image 192
mfulton26 Avatar answered Oct 20 '22 16:10

mfulton26