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
}