Search icon CANCEL
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Kotlin for Enterprise Applications using Java EE

You're reading from   Kotlin for Enterprise Applications using Java EE Develop, test, and troubleshoot enterprise applications and microservices with Kotlin and Java EE

Arrow left icon
Product type Paperback
Published in Nov 2018
Publisher Packt
ISBN-13 9781788997270
Length 388 pages
Edition 1st Edition
Languages
Tools
Arrow right icon
Author (1):
Arrow left icon
Raghavendra Rao K Raghavendra Rao K
Author Profile Icon Raghavendra Rao K
Raghavendra Rao K
Arrow right icon
View More author details
Toc

Table of Contents (13) Chapters Close

Preface 1. Kotlin – A First look FREE CHAPTER 2. Kotlin – The Game Changer 3. An Overview of Java EE and Kotlin 4. Kotlin with JSF and CDI 5. Kotlin with JPA and EJB 6. Enterprise Messaging with Kotlin 7. Developing RESTful Services with JAX-RS 8. Securing JAVA EE Applications with Kotlin 9. Implementing Microservices with Kotlin 10. Performance Monitoring and Logging 11. Design Patterns with Kotlin 12. Other Books You May Enjoy

Classes in Kotlin

Classes in Kotlin are created using the class keyword, which is depicted as follows:

class User {

}

The structure of the class is as follows:

Class className {
//properties and constructor
//member functions
}

Let's write a class for User.

Consider the following code for 14_Class.kts:

class User {
var name = "George"
}

val user = User()
println(user.name)

The output is as follows:

This class has a property called name. Classes are instantiated with just the class name, followed by parentheses. Note that there is no new keyword in Kotlin to create an object, unlike in Java.

Classes in Kotlin are final by default. We cannot extend from a class directly. To inherit from the classes, we have to open the classes explicitly. Classes need to have an open keyword in their declaration, as shown in the following code:

open class Person {

}

Alternatively, we can use all-open compiler plugins to make all the classes extendable or accessible to frameworks such as JPA and Spring. We will discuss compiler plugins further in the next chapter.

Constructors

Constructors are used to initialize class properties. As in Java, a constructor is a special member function that is invoked when an object is instantiated. However, they work slightly different in Kotlin.

In Kotlin, there are two constructors:

  • Primary constructor: This is a concise way to initialize the properties of a class
  • Secondary constructor: This is where additional initialization logic goes

The primary constructor is part of the class header. Here's an example:

class User() {

}

The block of code surrounded by parentheses is the primary constructor. Consider the following code for 14a_PrimaryConstructor.kts:

class User(var firstName: String, var lastName: String) {

}

val user = User("Norman", "Lewis")
println("First Name= ${user.firstName}")
println("Last Name= ${user.lastName}")

The output is as follows:

The constructor goes here as part of the class header. The constructor declares two properties—firstName and lastName. Let's look at another example for 14b_PrimaryConstructor.kts:

class User(var firstName: String, val id: String) {

}
val user = User("Norman", "myId")
println("First Name = ${user.firstName}")
println("User Id = ${user.id}")

The output of the preceding code is as follows:

For the primary constructor, properties have to be declared using var or val. Otherwise, the code fails to compile.

The secondary constructor is created using the constructor keyword. The class can declare a secondary constructor to initialize its properties. This is shown in the following code:

class AuditData {
constructor(message: String) {
//init logic
}
constructor(message: String, locale: String) {
// init logic
}
}

In the preceding code snippet, we wrote two constructors. One had a message as an argument and one had two arguments—message and locale. Consider the following code for 14c_SecondaryConstructor.kts:

var audit = AuditData("record added")
println("Message ${audit.message}")

audit = AuditData("record updated", "en-US")
println("Message: ${audit.message}")
println("Locale: ${audit.locale}")

When we call AuditData with only a message, the constructor with one argument will be invoked. Similarly, when we pass two arguments, a message and a locale, the constructor with two arguments will be invoked.

The output is as follows:

Static functions

Static functions are functions that can be invoked without creating multiple instances of a class. Static functions avoid code duplication and can be reused.

Let's take a look at how to write a static function in Kotlin.

Consider the following code for 15a_StaticMethods.kts:

object MyUtil {
fun foo(){
println("Static function foo() is invoked")
}
}

MyUtil.foo()

Note that we declared an object MyUtil and defined a function foo(). This is known as object declaration.

We invoked the function foo() directly using the object MyUtil.

The output of the preceding code is as follows:

There are different ways to write static functions in Kotlin. We can define a companion object inside a class and define a static function in it. Consider the following code for 15b_StaticMethods.kts:

class Person {
companion object {
fun foo(){
println("Static function foo() is invoked")
}
}
}
Person.foo()

The output is as follows:

We can also give a name to the companion object. Consider the following code for 15c_StaticMethods.kts:

class Person {
companion object Util {
fun foo(){
println("Static function foo() is invoked")
}
}
}
Person.Util.foo()

The output is as follows:

We can invoke the static method shown in the preceding example with companion as Person.Companion.foo(). The static method foo can be invoked using either the class name or a named companion object prefixed with the class name, such as Person.Util.foo().

In this section, we have covered the constructs that Kotlin provides. We will be using these constructs in the next few chapters.

You have been reading a chapter from
Kotlin for Enterprise Applications using Java EE
Published in: Nov 2018
Publisher: Packt
ISBN-13: 9781788997270
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at €18.99/month. Cancel anytime