[日更][05]-Kotlin

2023-08-14  本文已影响0人  代码多哥

因为时间很短,所以内容不是很复杂,写一个有价值的小知识,主要是为了保持每日学习和写作的习惯,大作还是会写到相关的主题里面,尽量做到周更。敬请关注本人的主要作品集:

一路向下之AOSP研究

为了能够最大限度的保证文章的质量,日更主要采用翻译的方法来完成。本系列将主要翻译Kotlin官网的内容。具体的地址

https://kotlinlang.org/docs/home.html

四 Basic types

Kotlin中的每个变量和数据结构都有一个数据类型。数据类型很重要,因为它们告诉编译器可以对该变量或数据结构执行什么操作。换句话说,它具有什么功能和属性。

在上一章中的例子中,Kotlin能知道customers的类型是:Int 。Kotlin推断数据类型的能力被称为类型推断。为customers赋一个整数值,由此,Kotlin推断出customers的类型是Int。因此,编译器知道您可以对customer执行算术运算。

var customers = 10

// Some customers leave the queue
customers = 8

customers = customers + 3 // Example of addition: 11
customers += 7            // Example of addition: 18
customers -= 3            // Example of subtraction: 15
customers *= 2            // Example of multiplication: 30
customers /= 3            // Example of division: 10

println(customers) // 10

在Kotlin中,总共有如下的基础类型

Category Basic types
Integers Byte, Short, Int, Long
Unsigned integers UByte, UShort, UInt, ULong
Floating-point numbers Float, Double
Booleans Boolean
Characters Char
Strings String

有关基本类型及其属性的更多信息,请参阅basic types

有了这些知识,您就可以声明变量并在以后初始化它们。只要变量在第一次读取之前初始化,Kotlin就可以管理它。
若要在不需要初始化的情况下声明变量,请使用“:”指定其类型。

例如:

// Variable declared without initialization
val d: Int
// Variable initialized
d = 3

// Variable explicitly typed and initialized
val e: String = "hello"

// Variables can be read because they have been initialized
println(d) // 3
println(e) // hello

Now that you know how to declare basic types, it's time to learn about collections.
现在您已经知道了如何声明基本类型,现在是时候学习collections.

译者注释:
1)Kotlin也是完全面向对象的,所有的基础类型都是Class,这与Java不一样。
2)Kotlin支持Unsigned 整形,这与Java也是有差别的。Java工程师可能需要额外学习一下。
3)变量的类型推导是一次性的,当推导为A后,就只能接受A类或者其子类的值,而不能赋值为别的类型。这与JS等弱类型语言还是不一样的。

上一篇 下一篇

猜你喜欢

热点阅读