dir.by  
Programming, development, testing
Kotlin
What is class in Kotlin? Example: class MyBook { ... }
  Looked at 1317 times    
 What is class in Kotlin? 
last updated: 3 February 2025
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:
используем 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!")
Example 1 with secondary constructor
  Kotlin  
class MyBook
{
     var bookText:String // field

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

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

fun main() {
     val book1 = MyBook("Hello!") // create an object

     book1.Show() // call the method
}
Note!
It's a secondary constructor, that's how the theory describes it, because it's inside a class
Example 2 with primary constructor
  Kotlin  
class MyBook(var bookText:String) // constructor and field in the same expression
{
     fun Show() // method
     {
          println(bookText.toString())
     }
}

fun main() {
     val book1 = MyBook("Hello!") // create an object

     book1.Show() // call the method
}
Notes
It is primary constructor
Example 3 with primary constructor and init block
  Kotlin  
class MyShop(name: String, street:String) {
     val shopName = "Welcome to $name"

     init {
          println("first block of initialization ... if need use $name")
     }

     val streetName = "good $street"

     init {
          println("second block of initialization ... if need use streetName")
     }
}

fun main() {

     val shop1 = MyShop("Book store", "Orange avenu") // create an object

}
Note!
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.
Example 4 with primary constructor and secondary constructor
  Kotlin  
class MyShop(val shopName:String) {

     private val shopFruits:MutableList<String> = mutableListOf()

     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
Note!
If the class has a primary constructor and a secondary constructor.
In this case, the secondary constructor must call the primary constructor using the word this
.
this(Parameters of the main constructor)
Example 5 There are no constructors, but there is a block init
  Kotlin  
class MyShop {

     private val shopFruits:MutableList<String> = mutableListOf()

     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
Note!
If a class does not have a primary constructor and a secondary constructor, the initialization block will still execute.
Example 6 no constructors and no block init
  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()

}
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.
 
← Previous topic
How do I find enum by value 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 project in IntelliJ IDEA for study 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 ?
Class
What is class in Kotlin? Example: class MyBook { ... }
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> { ... }
Collections and Arrays
Create collections list, set, map and an array array in Kotlin
null
null value, use the symbol ? and ?. and !! and ?: and !!. and ?. in Kotlin
Lambda function
Lambda function in Kotlin. Example 1: var myFunc1 : (a:Int, b:Int) -> Int = { p1, p2 -> p1 + p2 };

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