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 33
basic types and variables
基本类型和变量
var x = 5
你赋予变量的值用于创建新的对象。在本例中,你将数值
5
值给一个新的名为x的变量。由于编译器知道
5
是一个整数,因
此这行代码将会创建一个数值为
5
的整型对象:
Int
5
当你声明变量时会发生什么
编译器确实很关心变量类型,这样它才能防止可导致代码错误
的奇怪或危险的操作。例如,它不会让你将字符串“
Fish
”赋
值给一个整型变量,因为它知道对字符串进行数值计算显然是
不合适的。
为了使这种类型安全起作用,编译器需要知道变量的类型。编
译器可以通过该变量被赋予的值推测出变量的类型。
接下来让我们看看这种类型推测是如何实现的吧。
变量值被转换成一个对象
当你使用如下代码进行变量声明时:
编译器由对象的类型推断变量的类型
接下来编译器使用对象的类型作为变量的类型。在上面的例子
中,对象的类型是Int,所以变量的类型也是Int。变量的类
型将永远不变。
var Int
x
接着,该对象会被赋给变量。那么这一操作是如何实现的呢?
我们将在接下来的几页中
详细介绍几种类型
想要创建一个变
量,编译器需要
知道变量的名
、类型以及是
否可以被重用。
编译器知道你需要一个整型变量
这样才能匹配对象类型
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