Kotlin 简明教程

Kotlin - Data Types

Kotlin数据类型是对数据的分类,它告诉编译器编程人员如何打算使用数据。例如,Kotlin数据可以是数字、字符串、布尔值等。

Kotlin data type is a classification of data which tells the compiler how the programmer intends to use the data. For example, Kotlin data could be numeric, string, boolean etc.

Kotlin将所有内容都视为对象,这意味着我们可以在任何变量上调用成员函数和属性。

Kotlin treats everything as an object which means that we can call member functions and properties on any variable.

Kotlin是一种静态类型语言,这意味着每个表达式的类型都应在编译时已知。

Kotlin is a statically typed language, which means that the data type of every expression should be known at compile time.

Kotlin内置数据类型可分类如下:

Kotlin built in data type can be categorized as follows:

  1. Number

  2. Character

  3. String

  4. Boolean

  5. Array

(a) Kotlin Number Data Types

Kotlin数字数据类型用于定义保存数字值的变量,它们分为两组:(a) Integer types 存储整数,正数或负数(b) Floating point 类型表示带分数部分(包含一个或多个小数点)的数字。

Kotlin number data types are used to define variables which hold numeric values and they are divided into two groups: (a) Integer types store whole numbers, positive or negative (b) Floating point types represent numbers with a fractional part, containing one or more decimals.

下表列出了所有 Kotlin 数字数据类型、定义其变量类型的关键字、变量占用的内存大小以及可以在这些变量中存储的值范围。

Following table list down all the Kotlin number data types, keywords to define their variable types, size of the memory taken by the variables, and a value range which can be stored in those variables.

Data Type

Size (bits)

Data Range

Byte

8 bit

-128 to 127

Short

16 bit

-32768 to 32767

Int

32 bit

-2,147,483,648 to 2,147,483,647

Long

64 bit

-9,223,372,036,854,775,808 to +9,223,372,036,854,775,807

Float

32 bit

1.40129846432481707e-45 to 3.40282346638528860e+38

Double

64 bit

4.94065645841246544e-324 to 1.79769313486231570e+308

如果我们试图在特定数据类型的变量中存储一个大于允许值的值,Kotlin 编译器将会报错,因为在运行时会发生溢出。

If we will try to store a value more than permitted value in a variable of particular data type, the Kotlin compiler will complain because an overflow would occur at runtime.

Example

下面的示例展示了如何定义和访问不同的 Kotlin 数字数据类型:

Following example shows how to define and access different Kotlin number data types:

fun main(args: Array<String>) {
   val a: Int = 10000
   val d: Double = 100.00
   val f: Float = 100.00f
   val l: Long = 1000000004
   val s: Short = 10
   val b: Byte = 1

   println("Int Value is " + a)
   println("Double  Value is " + d)
   println("Float Value is " + f)
   println("Long Value is " + l )
   println("Short Value is " + s)
   println("Byte Value is " + b)
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Int Value is 10000
Double  Value is 100.0
Float Value is 100.0
Long Value is 1000000004
Short Value is 10
Byte Value is 1

(b) Kotlin Character Data Type

Kotlin 字符数据类型用于存储单个字符,它们用 Char 关键字表示。Char 值必须用单引号括起来,例如 'A' 或 '1'。

Kotlin character data type is used to store a single character and they are represented by the type Char keyword. A Char value must be surrounded by single quotes, like 'A' or '1'.

Example

以下示例展示了如何定义和访问 Kotlin Char 数据类型:

Following example shows how to define and access a Kotlin Char data type:

fun main(args: Array<String>) {
   val letter: Char    // defining a Char variable
   letter = 'A'        // Assigning a value to it
   println("$letter")
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

A

Kotlin 支持许多字符转义序列。当一个字符前有反斜杠 (\) 时,它就被称为转义序列,并且它对编译器有特殊含义。例如,以下语句中的 \n 是一个有效字符,称为换行符。

Kotlin supports a number of escape sequences of characters. When a character is preceded by a backslash (\), it is called an escape sequence and it has a special meaning to the compiler. For example, \n in the following statement is a valid character and it is called a new line character

println('\n') //prints a newline character

println('\$') //prints a dollar $ character

println('\\') //prints a back slash \ character

Kotlin 支持以下转义序列:\t、\b、\n、\r、\'、\"、\\ 和 \$。

The following escape sequences are supported in Kotlin: \t, \b, \n, \r, \', \", \\ and \$.

(c) Kotlin String Data Type

String 数据类型用于存储一组字符。String 值必须用双引号 (" ") 或三引号 (""" """) 括起来。

The String data type is used to store a sequence of characters. String values must be surrounded by double quotes (" ") or triple quote (""" """).

在 Kotlin 中,我们有两种字符串 - 一种称为 Escaped String ,另一种称为 Raw String

We have two kinds of string available in Kotlin - one is called Escaped String and another is called Raw String.

  1. Escaped string is declared within double quote (" ") and may contain escape characters like '\n', '\t', '\b' etc.

  2. Raw string is declared within triple quote (""" """) and may contain multiple lines of text without any escape characters.

fun main(args: Array<String>) {
   val escapedString : String  = "I am escaped String!\n"
   var rawString :String  = """This is going to be a
   multi-line string and will
   not have any escape sequence""";

   print(escapedString)
   println(rawString)
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

I am escaped String!
This is going to be a
   multi-line string and will
   not have any escape sequence

(d) Kotlin Boolean Data Type

布尔类型非常简单,就像其他编程语言一样。布尔数据类型只有两个值 - truefalse

Boolean is very simple like other programming languages. We have only two values for Boolean data type - either true or false.

fun main(args: Array<String>) {
   val A: Boolean = true   // defining a variable with true value
   val B: Boolean = false   // defining a variable with false value

   println("Value of variable A "+ A )
   println("Value of variable B "+ B )
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Value of variable A true
Value of variable B false

布尔类型有一个可空的对等类型 Boolean? ,它可以存储 null 值,如下所示:

Boolean has a nullable counterpart Boolean? that can store a null value as below:

val boolNull: Boolean? = null

(e) Kotlin Array Data Type

Kotlin 数组是同质数据的集合。与为每个值声明单独的变量不同,数组用于在单个变量中存储多个值。

Kotlin arrays are a collection of homogeneous data. Arrays are used to store multiple values in a single variable, instead of declaring separate variables for each value.

我们将在单独的章节中学习数组,现在让我们看一个示例,以定义一个整数数组,然后访问它的一个元素。

We will study array in a separate chapter, for now let’s look at one example to define an array of integers and then access its one of the elements.

fun main(args: Array<String>) {
   val numbers: IntArray = intArrayOf(1, 2, 3, 4, 5)
   println("Value at 3rd position : " + numbers[2])
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

Value at 3rd position : 3

Kotlin Data Type Conversion

类型转换是一个将一种数据类型的值转换为另一种类型的值的过程。Kotlin 不支持直接将一种数字数据类型转换为另一种数据类型,例如,无法将 Int 类型转换为 Long 类型:

Type conversion is a process in which the value of one data type is converted into another type. Kotlin does not support direct conversion of one numeric data type to another, For example, it is not possible to convert an Int type to a Long type:

fun main(args: Array<String>) {
   val x: Int = 100
   val y: Long = x  // Not valid assignment

   println(y)
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

main.kt:3:18: error: type mismatch: inferred type is Int but Long was expected
   val y: Long = x  // Not valid assignment

为了将一种数字数据类型转换为另一种类型,Kotlin 提供了一组函数:

To convert a numeric data type to another type, Kotlin provides a set of functions:

  1. toByte()

  2. toShort()

  3. toInt()

  4. toLong()

  5. toFloat()

  6. toDouble()

  7. toChar()

现在让我们再次重写上面的示例并尝试运行它:

Now let’s rewrite above example once again and try to run it:

fun main(args: Array<String>) {
   val x: Int = 100
   val y: Long = x.toLong()

   println(y)
}

当你运行上述 Kotlin 程序时,它将生成以下输出:

When you run the above Kotlin program, it will generate the following output:

100