Reputation: 140
I got a redeclaration error when I tried to create private Person class in both practice1.kt and practice2.kt files in the same project. For example:
Practice1.kt
private class Person constructor(var name: String, var age: Int){
var profession: String = "Not mentioned"
init{
println("$name's details are being held in this class object.")
}
constructor(name:String,age:Int, profession: String): this(name,age){
this.profession = profession
}
fun printPersonDetails(){
println("$name whose profession is $profession, is $age years old.")
}}
fun main(args: Array<String>){
val smith = Person("Smith",20)
smith.printPersonDetails()}
Practice2.kt
private class Person(val name:String, age:Int){
var age: Int = age
set(new_data){
println("Setting age to $new_data")
field = new_data
}}
I am getting error while creating the smith Person object in the main function in Practice1.kt saying: Cannot access 'Person': it is private in file.
I thought the private classes are visible only inside the containing file. Why is the private class in one file (practice1.kt) interfering with the private class of the other file(practice2.kt) ?
Upvotes: 3
Views: 668
Reputation: 147991
Basically, the error that you are facing is caused by the fact that you cannot have two classes under the same full qualified names (package name + class simple name, e.g. com.example.MyClass
where com.example
is the package of the class MyClass
).
This limitation is derived from the JVM architecture that prohibits its class loaders to load more than one class with the same FQN (if it faces such duplicates, it loads only one of them). Also, since class files are usually placed in the file system accordingly to their FQNs, the file paths for the duplicates would be the same. Anyway, allowing duplicate classes seems to lead to no good.
It's important to note that the scoping in your case is still correct: you cannot access the private
declarations in other files than the one that declares it (redeclaration is not a usage).
The workaround for your case is to move one of the files to a different package with a package declaration in the beginning:
package com.example
Upvotes: 6
Reputation: 312
I thought the private classes are visible only inside the containing file.
Even though the documentation states "If you mark a declaration private, it will only be visible inside the file containing the declaration", this does not appear to be true for classes
Since your classes are in the same package, to keep both classes, you can put them in different packages or give them different names.
Upvotes: 1