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 185
abstract classes and interfaces
抽象类接口
使用
as
进行显式转换
如果你想要访问某个潜在对象的行为,但编译器无法对其进行智
能转换,
你可以显式地将该对象转换成合适的类型。
假设你能够确定名为rRoamable类型变量保存的是Wolf对象的
引用。在这种情况下,你可以使用as操作符去复制一份Roamable
类型变量中保存的引用,并强制地将该引用赋给一个新的Wolf
型变量。然后你就可以使用该Wolf类型变量去访问Wolf的行为。
具体代码如下:
如果你不确定某个对象是否为一个Wolf对象,你可以像这样在转
换之前使用is操作符进行检查:
var wolf = r as Wolf
wolf.eat()
要注意的是wolfr变量保存着对同一个Wolf对象的引用。但是
r变量只知道这个对象实现了Roamable接口,而wolf变量知道该
对象本质是一个Wolf对象,所以可以视它为Wolf对象:
var Roamable
Wolf
引用
r
var Wolf
引用
wolf
if (r is Wolf) {
val wolf = r as Wolf
wolf.eat()
}
现在你已经了解了显式转换(和智能转换)是如何工作的,让我们再
更新一下Animal项目的代码
这段代码显式地将对象转换为
W
olf
类型
使你可以调用它的
W
olf
方法
虽然
r
变量保存了
Wolf
对象的引
但由于
r
变量是
Roamable
型的变量
所以你只能用它访问
潜在对象拥有的
R
oamable
类的任
意属性和方法 ...
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