dir.by  
  Поиск  
Компьютер, программы
Kotlin
 What is class in Kotlin? | Primary and secondary constructor | block init 
посмотрели 2364 раз
обновлено: 7 July 2026
Class in Kotlin can contain:
• Constructor (primary)
• Constructor (secondary)
• Initialization block init
• fields
• Properties
• Functions
• Nested Classes
There is no destructor in the class in Kotlin.

In general terms:
The class in Kotlin describes the object.
Kotlin program can be represented as interrelated objects.
Syntax
To define a class
Use the word class

  Kotlin  
class MyBook
{
   ...
}
To create a class object:
Use Class Name(parameters or no parameters)

  Kotlin  
MyBook("Hello!")


Note!
In other languages, the word new has always been used
In Java we wrote
  Java  
new MyBook("Hello!")
Primary and secondary constructor. Block init
Example 1.
Secondary constructor

  Kotlin  
class MyBook
{
     // Secondary constructor
     constructor(text:String)
     {
     }
}

Note!
The secondary constructor is so named because it is inside a class and is defined by the word constructor
  Kotlin  
class MyBook
{
     var bookText:String // field

     constructor(text:String) // Secondary constructor
     {
          bookText = text;
     }

     fun Show() // method
     {
          println(bookText.toString())
     }
}

fun main() {
     val book1 = MyBook("Hello!") // create an object, the secondary constructor will be called

     book1.Show() // call the method
}
Example 2.
Primary constructor

  Kotlin  
class MyBook constructor(var bookText:String)
{
}


 
 
 
 
 

 
 
 
 

Abridged version:
You can remove the word constructor
  Kotlin  
class MyBook(var bookText:String)
{
}
Note!
The singing constructor is called so because it is located in the class description
A primary constructor cannot contain executable code.
A class can have only one primary constructor.

  Kotlin  
class MyBook constructor(var bookText:String) // Primary constructor
{
     fun Show() // method
     {
          println(bookText)
     }
}

fun main() {
     val book1 = MyBook("Hello!") // create an object and the primary constructor will be called
     book1.bookText = "123" // Note! we can use bookText even here

     book1.Show() // call the method
}


Abridged version:
You can remove the word constructor
  Kotlin  
class MyBook(var bookText:String) // Primary constructor
{
     fun Show() // method
     {
          println(bookText)
     }
}
...


Attention! If you want to prohibit the use of bookText outside of a class, then you need to add private
  Kotlin  
class MyBook(privte var bookText:String) // Primary constructor
{
     fun Show() // method
     {
          println(bookText) // bookText can be used here
     }
}

fun main() {
     val book1 = MyBook("Hello!") // create an object and the primary constructor will be called
     book1.bookText = "123" // Mistake! Cannot access
}
Example 3.
Primary constructor and block init
Note!
A primary constructor cannot contain executable code.
If we need to execute some initializing code, it can be placed in the appropriate blocks, which are marked with the word init.
When you create a class object, the initialization blocks are executed in the order in which they go in the body of the class, interspersed with the initialization of properties.
  Kotlin  
class MyShop(name: String, street:String) // Primary constructor
{
     val shopName = "Hello $name"

     // block init
     init {
          println(shopName)
     }

     val streetName = "Go to $street"

     // block init
     init {
          println(streetName)
     }
}

fun main() {

     val shop1 = MyShop("Fruits market", "Turkey street 25") // create an object

}
Example 4.
Primary and secondary constructors
Note!
If a class has a primary constructor and a secondary constructor, then the secondary constructor must call the primary constructor using the word this.
this(Parameters of the primary constructor)

  Kotlin  
class MyShop(val shopName:String) // Primary constructor
{
     private val shopFruits:MutableList<String> = mutableListOf()

     // Secondary constructor
     constructor(fruits:List<String>, name:String) : this(name)
     {
          shopFruits.addAll(0, fruits)
     }

     fun Show()
     {
          println("$shopName has fruits:")
          for (item in shopFruits)
               println(item)
     }
}

fun main() {

     val shop1:MyShop = MyShop(listOf("orange", "banana"), "Market")
     shop1.Show()
}


Let's run the program and see the result:
Market has fruits:
orange
banana
Example 5.
There are no constructors, but there is a block init

  Kotlin  
class MyShop {

     // block init
     init {
          ...
     }
}

Note!
If a class does not have a primary and secondary constructor, block init will still execute.
  Kotlin  
class MyShop
{
     private val shopFruits:MutableList<String> = mutableListOf()

     // block init
     init {
          shopFruits.addAll(listOf("orange", "banana"))
     }
    
     fun Show()
     {
          for (item in shopFruits)
               println(item)
     }
}

fun main() {
     val shop1:MyShop = MyShop()
     shop1.Show()
}


Let's run the program and see the result:
orange
banana
Example 6.
No constructors and no block init
Note!
If a class does not have a primary constructor and does not have a secondary constructor, that class will automatically generate an empty, invisible constructor with no parameters.
The visibility of this constructor will be public.
  Kotlin  
class MyShop
{
     var shopFruits:MutableList<String> = mutableListOf()

     fun Show()
     {
          for (item in shopFruits)
               println(item)
     }
}

fun main() {

     val shop1:MyShop = MyShop()
     shop1.shopFruits.addAll(listOf("orange", "banana"))
     shop1.Show()
}
 
← Previous topic
Create collections list, set, map and an array array in Kotlin
 
Next topic →
lateinit is a late initialization for the class field | 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  
Яндекс.Метрика