Читать книгу Programming Kotlin Applications - Бретт Мак-Лахлин, Brett McLaughlin - Страница 67
Try to Anticipate How Types Will Be Used
ОглавлениеWhile that solution works, it's a bit inelegant. It is going to require every user of your Person
class—you included—to add that F
to decimals or to use the Float
type for variables passed into a constructor. And, as you just learned, Kotlin uses Double
as the default decimal type.
A better solution is to realize that if Kotlin defaults to Double
, maybe you should, too. (At least, unless you have a really good reason not to.) So change your Person
constructor to take in what most users will pass—a Double
created from a typed-in number:
class Person(var firstName: String, var lastName: String, var height: Double, var age: Int, var hasPartner: Boolean) {
Easy enough! And, because you've anticipated how users will create a new instance of Person
, you'll annoy your friendly developer comrades a lot less.
NOTE Don't forget to remove the F
from the two numbers in your main
function. If you don't, you'll get another error—this time from trying to pass a Float
into a constructor that expects a Double
.