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程序设计
你现在的位置 4 105
classes and objects
对象
到目前为止,你已经了解了如何通过类的构造函数来定义属性,以及如何在调
构造函数时为属性赋值。但是如果你想要做一些不同的事情呢?如果你想在
为属性赋值之前验证所赋的值的正确性呢?或者,如果你想要避免向构造函数
传递属性值,而使用通用的默认值来初始化属性,该怎么办?
想要了解如何完成这些任务,我们需要仔细研读构造函数的代码。
在这段代码中,构造函数的三个参数name_paramweight_param
breed_param均没有valvar前缀,这意味着构造函数并没有直接创建
新的属性。这些参数现在就和你之前见到的函数的定义中的参数一样。而
nameweightbreed属性则在类的主题中被定义。每个属性根据传入
构造函数中的参数值赋值。
那么,这种构造函数定义的方式怎么能让我们对属性进行更多的操作呢?
深入了解属性
Dog
构造函数背后的原理
就像你已经了解到的,我们现有的Dog构造函数代码为每个Dog对象定义了三
个属性:nameweightbreed,并且在其被调用时为属性进行了初始化赋
值:
class Dog(val name: String, var weight: Int, val breed: String) {
...
}
由于构造函数代码使用了快捷方式来执行这些操作,所以你仅需简洁的代码就
能完成这些任务。当
Kotlin
语言被开发出来时,它的开发者们认为定义和初始
化是一种常见的行为,并且他们认为简化定义和初始化的语法是有必要的。 ...
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