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程序设计
96
4
accessing members
如何访问属性及函数
var myDog = Dog("Fido", 70, "Mixed")
println(myDog.name)
一旦创建了对象,你就可使用点操作符(.)来访问它的属性。例
如,如果你想要打印Dogname,那么你可以使用如下代码:
myDog.bark()
你也可以更新任意一个使用var关键自定义的对象的属性。例如,
你可以使用如下代码将Dogweight属性值更新为
75
磅:
myDog.weight = 75
注意,编译器不允许你更新使用val定义的对象的属性值。当你尝
试更新val关键字定义的对象的属性时,会显示编译器错误。
你也可以使用点操作符来调用一个对象的函数。例如,如果你想
要调用Dogbark函数,那么你可以使用如下代码:
如果
Dog
对象在
Dog
数组中呢
你可以将任意对象加入数组中。例如,如果你想要创建一个Dog
数组,你可以使用如下代码
var dogs = arrayOf(Dog("Fido", 70, "Mixed"), Dog("Ripper", 10, "Poodle"))
这定义了一个名为dogs的变量,因为它包含了Dog对象,因此编译
器识别其类型为<Dog>。两个Dog对象被加入了该数组中。
你仍然可以访问数组中每个对象的属性及方法。例如,假设你想要
更新第二只Dogweight并且让其bark,你可以使用dogs[1]
访问dogs数组中第二个元素的引用,然后使用点运算符访问Dog
weight属性和bark ...
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