dir.by  
  Поиск  
Компьютер, программы
Kotlin
 Declare the variable and set the value in Kotlin | val, var, lateinit, constant: const val, global variable: companion object 
посмотрели 944 раз
обновлено: 12 July 2026
Example 1. Declare a variable with the modifier val inside class{ ... }
  Kotlin     The variable inside the class must be immediately set to
class Book
{
     val myName: String                      // compile error: myName must be initialized
     val myName1: String = ""             // declare the variable myName1 and set the empty text
}


  Kotlin     val means that we set the value only 1 time and CANNOT change the value.
class Book
{
     val myName1: String = ""             // declare the variable myName1 and set the empty text
     fun showValue1()
     {
          myName1 = "Hello"                 // compile error: val can not be reassigned
     }
}


  Kotlin     val means that we set the value only 1 time and CANNOT change the value.
class Book
{
     val myName2: String = "Hello"      // declare the variable myName2 and set the text Hello
     fun showValue2()
     {
          myName2 = "Evgen"                  // compile error: val can not be reassigned
     }
}


  Kotlin     The lateinit modifier cannot be used with val.
class Book
{
     lateinit val myName3: String        // compile error: 'lateinit' modifier is allowed only on mutable local variables
}


  Kotlin     In the variable declaration, add the ? symbol, and then the variable can be set to null, this is an empty value.
class Book
{
     val myName4: String = null          // compile error: null can not be a value
     val myName5: String? = null        // declare the variable myName5 and set null
}


  Kotlin     In the variable declaration, add the ? symbol, and then the variable can be set to null, this is an empty value. Remember that val means that we set the value only 1 time and CANNOT change the value.
class Book
{
     val myName5: String? = null        // declare the variable myName5 and set null
     fun showValue5()
     {
          myName5 = "Slava"                 // compile error: val can not be reassigned
     }
}


  Kotlin     In the variable declaration, add the ? symbol, and then the variable can be set to null, this is an empty value. Remember that val means that we set the value only 1 time and CANNOT change the value.
class Book
{
     val myName6: String? = "Hello"   // declare the variable myName6 and set the text Hello
     fun showValue6()
     {
          myName6 = "Thanks"                  // compile error: val can not be reassigned
     }
}
Example 2. Declare a variable with the modifier var inside class{ ... }
  Kotlin     The variable inside the class must be immediately set to
class Book
{
     var myName: String                      // compile error: myName must be initialized
     var myName1: String = ""             // declare the variable myName1 and set the empty text
}


  Kotlin     var means that we can change the variable many times.
class Book
{
     var myName1: String = ""             // declare the variable myName1 and set the empty text
     fun showValue1()
     {
          myName1 = "Hello"                  // set the text Hello
     }
}


  Kotlin     var means that we can change the variable many times.
class Book
{
     var myName2: String = "Hello"      // declare the variable myName2 and set the text Hello
     fun showValue2()
     {
          myName2 = "Evgen"                  // set the text Evgen
     }
}


  Kotlin     lateinit means that we can set the value later.
class Book
{
     lateinit var myName3: String        // declare the variable myName3.
     fun showValue3()
     {
          myName3 = "Hello"                     // set the text Hello
     }
}


  Kotlin     In the variable declaration, add the ? symbol, and then the variable can be set to null, this is an empty value.
class Book
{
     var myName4: String = null          // compile error: null can not be a value
     var myName5: String? = null        // declare the variable myName5 and set null
}


  Kotlin     In the variable declaration, add the ? symbol, and then the variable can be set to null, this is an empty value.
class Book
{
     var myName5: String? = null        // declare the variable myName5 and set null
     fun showValue5()
     {
          myName5 = "Hello"                  // set the text Hello
     }
}


  Kotlin     In the variable declaration, add the ? symbol, and then the variable can be set to null, this is an empty value.
class Book
{
     var myName6: String? = "Hello"   // declare the variable myName6 and set the text Hello
     fun showValue6()
     {
          myName6 = null                // install null
     }
}
Example 3. Declare a variable with the modifier val inside fun{ ... }
  Kotlin     You can then set the value of the variable inside the function. Note! The variable in the class must be immediately set to a value.
fun main()
{
     val myName: String            // declare the variable myName and then you can set the
     myName = "Hello"             // set the text Hello
     myName = "Evgen"            // compile error: val can not be reassigned
}


  Kotlin     val means that we set the value only 1 time and CANNOT change the value.
fun main()
{
     val myName1: String = ""             // declare the variable myName1 and set the empty text
     myName1 = "Hello"                 // compile error: val can not be reassigned
}


  Kotlin     val means that we set the value only 1 time and CANNOT change the value.
fun main()
{
     val myName2: String = "Hello"      // declare the variable myName2 and set the text Hello
     myName2 = "Evgen"                  // compile error: val can not be reassigned
}


  Kotlin     The lateinit modifier cannot be used with val.
fun main()
{
     lateinit val myName3: String        // compile error: 'lateinit' modifier is allowed only on mutable local variables
}


  Kotlin     In the variable declaration, add the ? symbol, and then the variable can be set to null, this is an empty value.
fun main()
{
     val myName4: String = null          // compile error: null can not be a value
     val myName5: String? = null        // declare the variable myName5 and set null
}


  Kotlin     In the variable declaration, add the ? symbol, and then the variable can be set to null, this is an empty value. Remember that val means that we set the value only 1 time and CANNOT change the value.
fun main()
{
     val myName5: String? = null        // declare the variable myName5 and set null
     myName5 = "Slava"                 // compile error: val can not be reassigned
}


  Kotlin     In the variable declaration, add the ? symbol, and then the variable can be set to null, this is an empty value. Remember that val means that we set the value only 1 time and CANNOT change the value.
fun main()
{
     val myName6: String? = "Hello"   // declare the variable myName6 and set the text Hello
     myName6 = "Thanks"                  // compile error: val can not be reassigned
}
Example 4. Declare a variable with the modifier var inside fun{ ... }
  Kotlin     You can then set the value of the variable inside the function. var means that we can change the variable many times. Note! The variable in the class must be immediately set to a value.
fun main()
{
     var myName: String            // declare the variable myName and then you can set the
     myName = "Hello"             // set the text Hello
     myName = "Evgen"           // set the text Evgen
}


  Kotlin     var means that we can change the variable many times.
fun main()
{
     var myName1: String = ""             // declare the variable myName1 and set the empty text
     myName1 = "Hello"                 // set the text Hello
}


  Kotlin     var means that we can change the variable many times.
fun main()
{
     var myName2: String = "Hello"      // declare the variable myName2 and set the text Hello
     myName2 = "Evgen"                  // set the text Evgen
}


  Kotlin     lateinit means that we can set the value later.
fun main()
{
     lateinit var myName3: String        // declare the variable myName3, and lateinit means that we can set the value later.
     myName3 = "Hello"                      // set the text Hello
}


  Kotlin     In the variable declaration, add the ? symbol, and then the variable can be set to null, this is an empty value.
fun main()
{
     var myName4: String = null          // compile error: null can not be a value
     var myName5: String? = null        // declare the variable myName5 and set null
}


  Kotlin     In the variable declaration, add the ? symbol, and then the variable can be set to null, this is an empty value. Remember that var means that we can change the variable many times.
fun main()
{
     var myName5: String? = null        // declare the variable myName5 and set null
     myName5 = "Slava"                 // set the text Slava[/textcolor]
}


  Kotlin     In the variable declaration, add the ? symbol, and then the variable can be set to null, this is an empty value. Remember that var means that we can change the variable many times.
fun main()
{
     var myName6: String? = "Hello"   // declare the variable myName6 and set the text Hello
     myName6 = "Thanks"                  // set the text Thanks
     myName6 = null                         // Set an empty value
}
Example 5. We declare the constant const val
const val is a constant and must be declared at the highest level (outside the class/function).
const val must match one of the primitive types (for example, Int) or the String type

  Kotlin  
const val myName1: String = "Hello my friend"     // declare the constant myName1 with the text

const val myPrice1: Int = 24                               // declare the constant myPrice1 with a value of 24

fun main()
{
     const val myName2: String = "Thank you"         // compile error: Modifier 'const' is not applicable to 'local variable'

     const val myPrice2: Int = 47                            // compile error: Modifier 'const' is not applicable to 'local variable'
}


Difference between val and const val:
The value of const val variables is set at compile time.
The value of const val of a variable must be assigned a value as soon as it is defined.
The value of val variables is set at run time
The value of val of the variable can be assigned later after the definition.
  Kotlin  
fun main() {
     val myName1: String
     // ...
     myName1 = "Hello"
}
Example 6. Declaring a global (static) file variable
Declaring a global variable at the highest level (outside the class/function)
You can use var and val.
A global variable (called a static variable in other programming languages).
A global variable means that this variable is created in memory only 1 time when the program is started and is terminated when the program is stopped.
The global variable is available everywhere (can be used in any class)

  Kotlin  
var booksCount: Int = 0            // declare a global variable
var filmsCount: Int = 0             // declare a global variable

class MyBook(bookName: String) {
     init {
          booksCount++          // use a global variable
     }
}

class MyFilm(bookName: String) {
     init {
          filmsCount++          // use a global variable
     }
}

fun main() {
     var book1 = MyBook("The three musketeers")
     var book2 = MyBook("House near lake")

     var film1 = MyFilm("Matrix")

     // use a global variable
     println(booksCount) // 2
     // use a global variable
     println(filmsCount) // 1
}
Example 7. Declare a global (static) class variable using companion object { ... }
Declare a global class variable using companion object:
  Kotlin  
class MyInfo {

     companion object {
          var booksCount: Int = 0       // declaring a global class variable
          var filmsCount: Int = 0       // declaring a global class variable
     }

}

You can use var and val.
A global variable (called a static variable in other programming languages).
A global variable means that this variable is created in memory only 1 time when the program is started and is terminated when the program is stopped.
The global variable is available everywhere (can be used in any class)

  Kotlin  
class MyInfo {

     companion object {
          var booksCount: Int = 0       // declaring a global class variable
          var filmsCount: Int = 0       // declaring a global class variable
     }

}

class MyBook(bookName: String) {
     init {
          MyInfo.booksCount++          // use a global variable
     }
}

class MyFilm(bookName: String) {
     init {
          MyInfo.filmsCount++          // use a global variable
     }
}

fun main() {
     var book1 = MyBook("The three musketeers")
     var book2 = MyBook("House near lake")

     var film1 = MyFilm("Matrix")

     // use a global variable
     println(MyInfo.booksCount) // 2

     // use a global variable
     println(MyInfo.filmsCount) // 1
}


На заметку!
Within companion object, you can also use the following methods:
  Kotlin  
companion object {
     var booksCount: Int = 0
     var filmsCount: Int = 0
     fun showMy() {
          println("books created: $booksCount, films created: $filmsCount")
     }
}
 
← Previous topic
Create a new console project to explore Kotlin | IntelliJ IDEA
 
Next topic →
null value, use the symbol ? and ?. and !! and ?: and !!. and ?. in Kotlin
 
Your feedback ... Comments ...
   
Your Name
Your comment (www links can only be added by a logged-in user)

  Объявления  
  Объявления  
 
What is Kotlin?
Why is IntelliJ IDEA the most popular development environment for Kotlin?
Download and install IntelliJ IDEA to explore Kotlin
Create a new console project to explore Kotlin | IntelliJ IDEA
Setting the value
Declare the variable and set the value in Kotlin | val, var, lateinit, constant: const val, global variable: companion object
null
null value, use the symbol ? and ?. and !! and ?: and !!. and ?. in Kotlin
Int, Float, Boolean, Char ...
Integer numbers in Kotlin are: Byte, UByte, Short, UShort, Int, UInt, Long, ULong
Decimal numbers in Kotlin are: Float, Double
A flag with values of true or false in Kotlin is: Boolean
The symbol in Kotlin is: Char
Convert number to text in Kotlin | Int → String
String
The string, the text in Kotlin is: String
Interpolate strings in Kotlin. Example: val address:String = "${street}, ${country}"
What is the difference between String and StringBuilder ?
Enum
What is an enumeration (enum) in Kotlin ?
How do I find enum by value in Kotlin ?
Function
fun() { ... } is a function in Kotlin. The function is needed to perform an action.
Lambda function
Lambda function in Kotlin. Example 1: var myFunc1 : (a:Int, b:Int) -> Int = { p1, p2 -> p1 + p2 };
Collections and Arrays
Create collections list, set, map and an array array in Kotlin
Class
What is class in Kotlin? Example: class MyBook { ... } | Primary and secondary constructor | block init
lateinit is a late initialization for the class field | Kotlin
class that inherits from interface in Kotlin | Example: class MyBook : IBook { ...}
Unnamed class that inherits from interface in Kotlin | Example: val book1 = object : IBook { ...}
Generic, template class in Kotlin | Example: class MyBook<T> { ... }
Writing a program
The Kotlin console app works like Android Jetpack Compose

  Ваши вопросы присылайте по почте: info@dir.by  
Яндекс.Метрика