In this tutorial you will learn about Variables via simple step by step examples.
Example 1: Variables
Let us look at a simple Variables example written in Kotlin Programming Language. Follow the following steps:
Step 1: Create Project
- Open your favorite Kotlin IDE.
- In the menu go to
File --> Create New Project
.
Step 2: Add Dependencies
No dependencies are needed for this project.
Step 3: Write Code
Our code will comprise the following Kotlin files:
Variables.kt
- In your editor or IDE, create a file known as
Variables.kt
. - Then add the following code:
(a). Variables.kt
package Variables
//There are two type of variable declarations in kotlin, mutable and immutable.
//use var declaration for mutable variables and val for immutable variables
fun main(args : Array<String>) {
var message = "var means a mutable variable so you can change it. "
println("'message' variable has this value '$message'")
message = "wallah, modified"
println("now 'message' has this value '$message'")
println("")
val forever = "val means that the variable is immutable. If you try to modify this 'forever' variable, the compiler will complain."
println(forever)
//immutable = "oi" -- bzz, wrong!
}
Step 4: Run
Copy the code, build and run.
Reference
Here are the reference links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code: Apache 2.0 License |
Kotlin Var And Val Examples
Let us look at a simple Var And Val examples written in Kotlin Programming Language. Follow the following steps:
Step 1: Create Project
- Open your favorite Kotlin IDE.
- In the menu go to
File --> Create New Project
.
Step 2: Add Dependencies
No dependencies are needed for this project.
Step 3: Write Code
Our code will comprise the following Kotlin files:
AVarIsMutable.kt
Vals.kt
Vars.kt
Example 1: Var And Val
- In your editor or IDE, create a file known as
AVarIsMutable.kt
. - Then add the following code:
(a). AVarIsMutable.kt
// VarAndVal/AVarIsMutable.kt
fun main() {
var sum = 1
sum = sum + 2
sum += 3
println(sum)
}
/* Output:
6
*/
Example 2: Vals
- Next create another file known as
Vals.kt
. - And add the following code:
(b). Vals.kt
// VarAndVal/Vals.kt
fun main() {
val whole = 11
// whole = 15 // Error // [1]
val fractional = 1.4
val words = "Twas Brillig"
println(whole)
println(fractional)
println(words)
}
/* Output:
11
1.4
Twas Brillig
*/
Example 3: Vars
- Next create another file known as
Vars.kt
. - And add the following code:
(c). Vars.kt
// VarAndVal/Vars.kt
fun main() {
var whole = 11 // [1]
var fractional = 1.4 // [2]
var words = "Twas Brillig" // [3]
println(whole)
println(fractional)
println(words)
}
/* Output:
11
1.4
Twas Brillig
*/
Step 4: Run
Copy the code, build and run.
Reference
Here are the reference links:
Number | Link |
---|---|
1. | Download Example |
2. | Follow code author |
3. | Code License |