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

LISTING 1.1: A simple Kotlin program using classes and lists

Оглавление

data class User(val firstName: String, val lastName: String) fun main() { val brian = User("Brian", "Truesby") val rose = User("Rose", "Bushnell") val attendees: MutableList<User> = mutableListOf(brian, rose) attendees.forEach { user -> println("$user is attending!") } }

Take a minute or two to read through this code. Even if you've never looked at a line of Kotlin before, you can probably get a pretty good idea of what's going on. First, it defines a User class (and in fact, a special kind of class, a data class; more on that later). Then it defines a main function, which is pretty standard fare. Next up are two variables (or vals), each getting an instance of the User class defined earlier. Then a list is created called attendees and filled with the two users just created. Last up is a loop through the list, doing some printing for each.

If you ran this code, you'd get this rather unimpressive output:

User(firstName=Brian, lastName=Truesby) is attending! User(firstName=Rose, lastName=Bushnell) is attending!

Obviously, parts of this probably look odd to you, whether you're brand new to writing code or an experienced Java pro. On top of that, it's likely you have no idea how to actually compile or run this code. That's OK, too. We'll get to all of that.

NOTE It bears repeating: You really don't need to understand the code in Listing 1.1. This book assumes you've programmed at least a little bit—and it's true that you'll likely understand Kotlin a bit faster if you have a Java background—but you will pick up everything you see in Listing 1.1 (and quite a bit more) just by continuing to read and working through the code samples. Just keep going, and you'll be programming in Kotlin in no time.

For now, though, here's the point: Kotlin is really approachable, clean to read, and actually a pretty fun language to use. With that in mind, let's get some basics out of the way so you can get to writing code, not just looking at it.

Programming Kotlin Applications

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