Читать книгу Programming Kotlin Applications - Бретт Мак-Лахлин, Brett McLaughlin - Страница 56

Classes: The Ultimate Type in Kotlin

Оглавление

Before getting further into Kotlin types—something this chapter is going to spend the rest of its time on—it's worth saying that classes are really the ultimate type in Kotlin. A class provides you a way to collect data and work with that data in a specific manner, and to model things in the world: numbers, sentences, objects like cars, people, even abstract ideas like a radio wave or a decision.

Classes also give you a pointer into something that's quite important in Kotlin: type safety. Type safety refers to the degree to which a programming language keeps you from making mistakes related to assigning one type (like a number) to a variable that should only hold letters. There's nothing as frustrating as treating a variable like it's all letters, and things in your program break because it turns out that that variable actually contains an instance of Person (or Car, or User, or something else that doesn't at all act like letters).

And that's where classes and objects are so key to type safety. Your Person is now strongly typed; you can't create an integer and shove a string into it. More specifically, you can't create a Car and shove it into a Person. You're going to see a lot more about this as the chapter goes on. For now, though, just think of objects as a really powerful way to be sure a variable (whether by val or by var) has exactly in it what you need.

NOTE If you're wondering how Kotlin actually knows what type is allowed for a variable, keep reading. Much more on that shortly.

Programming Kotlin Applications

Подняться наверх