The Programmers Guide To Kotlin - The Class & The Object |
Written by Mike James | |||||||
Tuesday, 29 October 2024 | |||||||
Page 3 of 6
Late Initialized PropertiesMuch of this chapter has been about setting up and initializing properties. If the property is a non-null type then it has to be initialized in the constructor code. However, there are case where the property is more correctly initialized by some other function. You can deal with this by initializing the property to a default value, or you can use a nullable type and have to deal with null checks from then on or you can mark the property with lateinit. This only works for var non-null, non-primitive properties defined in the body of the class. The property can remain undefined for as long as you like, but if you try to access it before it is initialized you will generate an exception. For example: class MyClass { lateinit var myMessage: String fun setMessage() { myMessage = "Message of the day" } } In this case it is supposed that the setMessage function will be called before the property is used. If you use it uninitialized: var myObject = MyClass() println(myObject.myMessage) then you will see the error message: Exception in thread "main" kotlin. UninitializedPropertyAccessException: etc.. However if you initialize it: var myObject = MyClass() myObject.setMessage() println(myObject.myMessage) everything works. Inner ClassesClasses can have functions and properties as members, and they can also have other classes. A nested class is defined within another class. It is local to the containing or outer class in that it isn't visible outside of the containing class. For example, MyNestedClass is local to MyClassA: class MyClassA { class MyNestedClass { fun myInnerMethod() { println("myMethod") } } fun myOuterMethod() { var myNestedObject = MyNestedClass() myNestedObject.myInnerMethod() } } It can be used by methods inside MyClassA, but it is inaccessible from anywhere else. By default nested classes cannot access the members of the outer class. That is, if you try: class MyClassA { you will find that myString is unresolved and there is an error. However, if you mark the nested class as inner then it can access the outer class's members. That is, with the addition of inner, myInnerMethod can now access myString in the outer class: class MyClassA { Inner classes are useful if you need to define classes that are useful to another class, but not more generally useful. If you need to instantiate a lot of inner class objects then it makes sense. However, if you only need a single instance then using a Kotlin object, see the next section, makes better sense as you don't have to declare a class first.
|
|||||||
Last Updated ( Tuesday, 29 October 2024 ) |