Constructors

Just like in Java, a class can have multiple constructors but, in Kotlin, the primary constructor can be added as part of the header of the class.

As an example, let's add a constructor to the HelloKotlin class:

import kotlinx.android.synthetic.main.activity_main.*

class
HelloKotlin constructor(message: String) {

fun displayKotlinMessage(view: View) {
Snackbar.make(view, "Hello Kotlin!!",
Snackbar.LENGTH_LONG).setAction("Action", null).show()
}
}

In the previous code, the HelloKotlin class has a primary constructor that takes a string called message.

Since the constructor does not have any modifiers, we can rid it of the constructor keyword altogether:

class HelloKotlin (message: String) {

fun displayKotlinMessage(view: View) {
Snackbar.make(view, "Hello Kotlin!!",
Snackbar.LENGTH_LONG).setAction("Action", null).show()
}

}

In Kotlin, secondary constructors have to call the primary constructor. Let's take a look at the code:

class HelloKotlin (message: String) {

constructor(): this("Hello Kotlin!!")

fun displayKotlinMessage(view: View) {
Snackbar.make(view, "Hello Kotlin!!",
Snackbar.LENGTH_LONG).setAction("Action", null).show()
}
}

A few things to note about the secondary constructor:

  • It does not take any parameters.
  • It calls the primary constructor with a default message.
  • It does not make use of the curly braces. This is because it has no body and therefore has no use for the curly braces. If we add a body, we'll be required to make use of the curly braces.

What if the displayKotlinMessage() method wants to make use of the message parameter passed in the constructor?

There are two ways to go about this. You can create a field in HelloKotlin and initialize it with the message parameter passed:

class HelloKotlin (message: String) {

private var msg = message

constructor(): this("Hello Kotlin!!")

fun displayKotlinMessage(view: View) {
Snackbar.make(view, msg,
Snackbar.LENGTH_LONG).setAction("Action", null).show()
}
}

You can also add the appropriate keyword to the message parameter to make it a field of the class as well:

class HelloKotlin (private var message: String) {

constructor(): this("Hello Kotlin!!")

fun displayKotlinMessage(view: View) {
Snackbar.make(view, message,
Snackbar.LENGTH_LONG).setAction("Action", null).show()
}
}

Let's take the changes we've made for a spin. In the onCreate() method in the MainActivity class, let's replace the HelloKotlin initialization:

HelloKotlin().displayKotlinMessage(view)

We'll replace it with an initialization that passes a message as well:

HelloKotlin("Get ready for a fun game of Tic Tac Toe").displayKotlinMessage(view)

The message passed is shown at the bottom when we click on the FloatingActionButton.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset