- Kotlin Programming By Example
- Iyanu Adelekan
- 382字
- 2021-08-27 20:00:07
Variables
A variable is an identifier for a memory location that holds a value. A simpler way to describe a variable is an identifier that holds a value. Consider the following program:
fun main(args: Array<String>) {
var x: Int = 1
}
The preceding x is a variable and the value it holds is 1. More specifically, x is an integer variable. The x is referred to as an integer variable because x has been defined to have the Int data type. As such, the x variable can only hold an integer value. To be more accurate, we say that x is an instance of the Int class. At this point, you must be wondering what the words instance and class mean in this context. All will be revealed in due time. For now, let's focus on the topic of variables.
When defining a variable in Kotlin, we make use of the var keyword. This keyword specifies that the variable is mutable in nature. Thus, it can be changed. The data type of the declared variable comes after a semicolon that follows the variable's identifier. It is important to note that the data type of a variable need not be explicitly defined. This is because Kotlin supports type inference—the ability to infer types of objects upon definition. We might as well have written the definition of our x variable as:
var x = 1
The outcome of the definition would be the same. A semicolon can be added to the end of the line of our variable definition but, similar to languages like JavaScript, it is not required:
var x = 1 // I am a variable identified by x and I hold a value of 1
var y = 2 // I am a variable identified by y and I hold a value of 2
var z: Int = x + y // I am a variable identified by z and I hold a value of 3
If we don't want the values of our variables to change over the course of the execution of our program, we can do so by making them immutable. Immutable variables are defined with the val keyword, as follows:
val x = 200
- DB2 V9權威指南
- FuelPHP Application Development Blueprints
- Learning Java Functional Programming
- JavaScript語言精髓與編程實踐(第3版)
- Java EE框架整合開發入門到實戰:Spring+Spring MVC+MyBatis(微課版)
- Web Application Development with R Using Shiny(Second Edition)
- Android NDK Beginner’s Guide
- Java Web基礎與實例教程
- Android系統原理及開發要點詳解
- Learning R for Geospatial Analysis
- Julia for Data Science
- JavaScript動態網頁編程
- Learning Python Data Visualization
- Learning C++ by Creating Games with UE4
- Python 快速入門(第3版)