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程序设计
42
2
more type conversions
小心溢出
试图将一个大的数值放入一个容量较小的变量中就好比试
图将桶装咖啡倒入小茶杯中。有些咖啡会被倒入茶杯中,
但是有些会溢出。
假如你想将Long的值放入Int中。正如我们之前所提到
的,Long可以容纳比Int更大的数字。
因此如果Long的值在Int可存储的范围之内,那么从Long
转换为Int是没有问题的。例如,将一个值为
42
Long
换为Int将得到一个值为
42
Int
var x = 123.456
var y: Int = x.toInt() //值为123
var x = 1234567890123
var y: Int = x.toInt() //值为1912276171!
这里的关键是,当你进行数值类型之间的相互转换时,请确保
你想转换的类型能够存储当前的变量值,否则你的代码可能会
得到意外的结果。
至此,你已经了解了变量的工作原理并且对
Kotlin
的基本类型有
了一定的经验。请尝试完成下面的练习。
这涉及数值正负
位运算
二进制等其他一些计算
机知识
在此不赘述
如果你对此感兴趣
可以搜
2
的补数
”。
var x = 42L
var y: Int = x.toInt() //值为42
但是如果Long的值超出了Int能容纳的范围,那么编译
器将会舍弃超出的部分,此时你会得到一个奇怪(仍可计
算)的数值。例如,当你将一个值为
1 234 567 890 123
Long转换Int时,你的Int变量的值会为
1 912 276 171
编译器假设这是你有意而为之,因此可以正常编译。如果你希望 ...
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