5/7/2023 0 Comments Kotlin weak referenceWorks, even though myObject is read-only. Notice, however, that the object instance that myObject references can have its properties changed even if referenced by a val. Would be indicated as a compile time error because you are trying to change the contents of myObject, which is read-only.Īs most of the time you don’t change object references, it is a good idea to use val on all variables that are used in object declarations. Then myObject would be read-only and: myObject = M圜lass2() If you had defined myObject as: val myObject = M圜lass1() That is, you can write: myObject = M圜lass2()Īnd now myObject references an instance of M圜lass2. ![]() As it is declared using var, this reference can change. Then myObject stores a reference to an instance of M圜lass1. All val promises is that the variable itself is read-only, and this is a very weak form of immutable.įor example, if you declare an instance as: var myObject = M圜lass1() ![]() Notice that although you will hear var described as mutable and val as immutable, this isn't accurate. ![]() In most cases you should use va r for simple types and val for objects.Ī more general principle, however, is to always use val unless you are forced to use var by the nature of the algorithm. Then you get a read-only variable which you cannot use on the left of an assignment. Then you will get a true variable that you can read and write. It is important to notice that there are two ways to declare a variable – var and val. ![]() Although it seemed sensible to dive into functions right at the start, because otherwise you can't even make sense of “Hello World”, there are some more basic things to look at.
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |