how to define variable in kotlin

Defining Variables in Kotlin

To define a variable in Kotlin, you can use the val and var keywords. Here's an explanation for each step:

  1. Using val Keyword:
  2. The val keyword is used to declare a read-only (immutable) variable. Once assigned, its value cannot be changed.
  3. Example: kotlin val pi = 3.14
  4. This declares a variable pi with the value 3.14.

  5. Using var Keyword:

  6. The var keyword is used to declare a mutable variable whose value can be changed after it is assigned.
  7. Example: kotlin var radius = 5
  8. This declares a variable radius with the initial value of 5, which can be changed later in the code.

  9. Type Inference:

  10. In Kotlin, you can omit the variable's type if it can be inferred from the value assigned to it.
  11. Example: kotlin val message = "Hello, World!"
  12. Here, the type of message is inferred as String because it is initialized with a string value.

  13. Explicitly Specifying Type:

  14. You can also explicitly specify the type of the variable when declaring it.
  15. Example: kotlin val number: Int = 10
  16. This declares a variable number of type Int with the initial value of 10.

  17. Nullable Variables:

  18. In Kotlin, you can declare variables as nullable by using the ? operator after the type.
  19. Example: kotlin var name: String? = null
  20. Here, name is a nullable variable of type String that can hold a null value.

  21. Lazy Initialization:

  22. You can also declare a variable without initializing it immediately by using the lateinit keyword.
  23. Example: kotlin lateinit var userName: String
  24. This declares a variable userName of type String that will be initialized later in the code.

  25. Variable Naming:

  26. Variable names in Kotlin can contain letters, digits, and underscores. They cannot start with a digit.
  27. Example: kotlin val userAge = 25

These are the various ways to define variables in Kotlin, allowing for flexibility and type safety in your code.