We can add properties to our classes in a couple of different ways. Let's start by adding a title property to our Course class, as follows:
class Course(courseTitle: String) {
val title = courseTitle
}
There are a couple of things to note here:
- We've added a primary constructor to pass the courseTitle parameter.
- We then define and initialize the title property using the value of courseTitle.
The primary constructor is defined by the parentheses after the class name. The primary constructor can be considered the default way of creating your class and can often be the only constructor that needs to be defined. We'll explore primary and secondary constructors in more detail later in this section in Customizing construction.
Now that we've updated our class definition, we can create a new instance by passing in a title for our course, shown as follows:
// create new instance of Course
val course = Course("Mastering Kotlin")
val courseTitle = course.title
After passing in courseTitle to our constructor and instantiating the class, we can access the title property directly by referencing its name.
Any exposed properties which can be accessed from Kotlin may also be accessed when working in Java. This example demonstrates how the properties of Kotlin classes will have getters/setters generated for them when calling from Java:
public static void main() {
Course course = new Course("Mastering Kotlin");
String courseTitle = course.getTitle();
}
You'll notice, in the preceding example, that the title property has no visibility modifier applied to it. In Kotlin, properties are public by default and available to any calling code. We'll explore Kotlin's other visibility modifiers later in this chapter.
Now that we've seen a simple example of adding and accessing a class property, let's dive deeper into how properties are treated by the Kotlin compiler.