New to Kotlin and way rusty on Java but I am trying to accomplish the instantiation of a inner Singleton object which uses a outer class variable to construct:
class Foo(inpoint: String) {
val point: Path
val bar: Bar
object Bar {
val content: String
init {
content = point.toFile().readText()
}
}
init {
point = Paths.get(inpoint)
bar = Bar
}
}
I get an error on the Singleton Bar
init trying to get the Foo
point (Path)
CodePudding user response:
Here point
is a member variable of class Foo
. Every object of this class will have its own copy of this variable. So it can only be accessed from an object of this class.
Bar
on the other hand is a static class. It belongs to class Foo
and not to an object of Foo
.
If you want to access point
inside Bar
, you will have to put it inside Bar
definition but then you will only have one copy of point
throughout the program.
object Bar {
private lateinit var point: Path
private lateinit var content: String
fun setPoint(inpoint: String) {
point = Paths.get(inpoint)
content = point.toFile().readText()
}
}