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

LISTING 2.4: Filling out your Person instances

Оглавление

import org.wiley.kotlin.person.Person fun main() { // Create a new person val brian = Person("Brian", "Truesby", 68.2, 33, true) println(brian) // Create another person val rose = Person("Rose", "Bushnell", 56.8, 32, true) println(rose) // Change Rose's last name rose.lastName = "Bushnell-Truesby" println(rose) }

Your results are likely not what you expected. You probably got a couple of errors like this:

Error:(5, 44) Kotlin: The floating-point literal does not conform to the expected type Float Error:(9, 43) Kotlin: The floating-point literal does not conform to the expected type Float

What in the world does this mean? If you find the line (the first number in the parentheses) and the place on that line (position 44), you'll see that the error occurs here:

val brian = Person("Brian", "Truesby", 68.2, 33, true)

You're passing in a decimal for height—in this case 68.2—which seems right. Here's the constructor in Person :

class Person(var firstName: String, var lastName: String, var height: Float, var age: Int, var hasPartner: Boolean) {

So what gives? The problem is that Kotlin is not converting types. A few things are actually happening here:

1 You give Kotlin the value 68.2. Kotlin sees a decimal number and automatically uses the Double type. This is important! Anytime a decimal is not given an explicit type, Kotlin will use Double.

2 The Double is passed into the Person constructor. However, Person is expecting a Float.

3 Kotlin will not try to convert between these two types—even though, in this case, they are compatible! Instead, Kotlin insists on strong typing, and throws an error.

Programming Kotlin Applications

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