Here is the example:
Declare inside the class
class User {
private val greeting = "Hello, World!"
}
Declare outside the class
private val greeting = "Hello, World!"
Here is the example:
Declare inside the class
class User {
private val greeting = "Hello, World!"
}
Declare outside the class
private val greeting = "Hello, World!"
The property declared inside the class is part of that class. This means that each instance of the class has its own version of the property, separate from the others. (Conversely, if you never create any instances of the class, there are no versions of that property anywhere.)
Because it's private, you can access it only from with the class; it's not visible to any other code.
In this case, because it's a val with a constant initialiser, each instance will get a reference to the same string, so you might think it's a bit pointless. But it can still be a good way to restrict access to the property, and make its connection to the class obvious to anyone reading it.
The property declared outside the class is a top-level property. This belongs to the package, and is the nearest thing Kotlin has to a global. There is exactly one of these. (So each instance of User would refer to the same greeting — though again, because it's a val with a constant initialiser, that doesn't make any practical difference in this case.)
You can access it from anywhere in that file, but because it's private it's not visible to code in any other file.
This boils down to the fact that Kotlin allows you to create files that do not contain classes, but only "top level" declarations. See their userguide.
Or, in other words:
A top level declaration is a function or property which is defined outside any class, object, interface or other structure.
(from here)
Thus: there is a fundamental difference. Your first example is a field that only exists in the scope of that class. The other one is a well, module wide private variable.