Chapter 4. classes and objects: A Bit of Class
It’s time we looked beyond Kotlin’s basic types.
Sooner or later, you’re going to want to use something more than Kotlin’s basic types. And that’s where classes come in. Classes are templates that allow you to create your own types of objects, and define their properties and functions. Here, you’ll learn how to design and define classes, and how to use them to create new types of objects. You’ll meet constructors, initializer blocks, getters and setters, and you’ll discover how they can be used to protect your properties. Finally, you’ll learn how data hiding is built into all Kotlin code, saving you time, effort and a multitude of keystrokes.
Object types are defined using classes
So far, you’ve learned how to create and use variables from Kotlin’s basic types, such as numbers, Strings and arrays. You know, for example, that when you write the code:
var x = 6
this creates an Int object with a value of 6, and a reference to the object is assigned to a new variable named x:
Behind the scenes, these types are defined using classes. A class is a template that defines what properties and functions are associated with objects of that type. When you create an Int object, for example, the compiler checks the Int class and sees that ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access