Skip to Content
Head First Kotlin程序设计
book

Head First Kotlin程序设计

by Dawn Griffiths, David Griffiths
August 2020
Intermediate to advanced
483 pages
11h 24m
Chinese
China Machine Press
Content preview from Head First Kotlin程序设计
108
4
initialize properties before you use them
你必须初始化所有属性
在第
2
章中,你已经了解到每一个在函数中使用的变量都必须被初
始化。这条规则对于类同样适用:你必须在使用类的属性前对其进
行初始化。初始化属性十分重要,如果你在属性声明或初始化块中
声明属性而没有初始化它,编译器将无法正常编译代码。例如,下
面的代码示例将无法被正常编译。这是因为我们在加入新的名为
temperament属性时没有对其进行初始化:
class Dog(val name: String, var weight: Int, breed_param: String) {
var activities = arrayOf("Walks")
val breed = breed_param.toUpperCase()
var temperament: String
...
}
你可以在几乎任意时刻对属性分配默认值。例如,在上面的例子
中,你可以将temperament属性初始化为"",此时代码将能正常
编译,如下代码所示:
var temperament = ""
由于
temperament
属性没有被初始化
所以这段代码不能被编译
这会将
temperament
属性初始化为空的字符串
:
Java
你不需要初始化类中所定义的变量
Kotlin
中有没有方法可以不初始化类的属性
:
如果你无法在类的初始化时为属性分配初始值
你可以使用
lateinit作为前缀
这告诉编译器你知道
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

More than 5,000 organizations count on O’Reilly

AirBnbBlueOriginElectronic ArtsHomeDepotNasdaqRakutenTata Consultancy Services

QuotationMarkO’Reilly covers everything we've got, with content to help us build a world-class technology community, upgrade the capabilities and competencies of our teams, and improve overall team performance as well as their engagement.
Julian F.
Head of Cybersecurity
QuotationMarkI wanted to learn C and C++, but it didn't click for me until I picked up an O'Reilly book. When I went on the O’Reilly platform, I was astonished to find all the books there, plus live events and sandboxes so you could play around with the technology.
Addison B.
Field Engineer
QuotationMarkI’ve been on the O’Reilly platform for more than eight years. I use a couple of learning platforms, but I'm on O'Reilly more than anybody else. When you're there, you start learning. I'm never disappointed.
Amir M.
Data Platform Tech Lead
QuotationMarkI'm always learning. So when I got on to O'Reilly, I was like a kid in a candy store. There are playlists. There are answers. There's on-demand training. It's worth its weight in gold, in terms of what it allows me to do.
Mark W.
Embedded Software Engineer

You might also like

面向对象的思考过程(原书第5版)

面向对象的思考过程(原书第5版)

马特 魏斯费尔德
GraphQL 学习指南

GraphQL 学习指南

Eve Porcello, Alex Banks
前端架构设计

前端架构设计

Micah Godbolt

Publisher Resources

ISBN: 9787111662358