Content preview from Head First Kotlin程序设计

这是新的一章 219
空值和异常
8
使代码安然无恙
每个人都想编写安全的代码。
好消息是
Kotlin
的设计本身就是代码安全的
。
我们首先为你展示
Kotlin
如何使用可空类型
,
这意味着你在
Kotlin
小城逗留期间几乎不会遇到空指针异常
。
你将学习如何进行安全调用
,
以及如何使用
K
otlin
的
Elvis
操作符避免惊慌失措
。
当我们介绍完空值后
,
你将学会如何像专
业人士那样抛出和捕获异常
。
Oh, Elvis! I know
my code is safe with
you.
从变量中删除对象引用
220
用空值删除一个对象引用
221
你可以在任何能够使用非可空类型的地方使用可空类型
222
创建一个可空类型的数组
223
访问可空类型的方法和属性
224
通过安全调用确保一切安全
225
链式安全调用
226
你可以使用安全调用赋值
228
如果变量的值不为空,使用
let
执行代码
231
对数组项使用
let 232
替代
if
表达式
233
使用
!!
操作符故意抛出
NullPointerException 234
创建
Null V
alues
项目
235
在异常情况下抛出异常
239
使用
try/catch
捕获异常
240
使用
finally
去做无论如何你都想做的事情
241
异常是
Exception
类型的对象
242
你可以显式地抛出异常
244
try
和
throw
都是表达式
245
Kotlin工具箱
250
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
O’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.
I 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.
I’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.
I'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.
Publisher Resources
ISBN: 9787111662358