Sign In Start Free Trial
Account

Add to playlist

Create a Playlist

Modal Close icon
You need to login to use this feature.
  • Book Overview & Buying Kotlin Programming Cookbook
  • Table Of Contents Toc
  • Feedback & Rating feedback
Kotlin Programming Cookbook

Kotlin Programming Cookbook

By : Aanand Shekhar Roy , Rashi Karanpuria
3.3 (3)
close
close
Kotlin Programming Cookbook

Kotlin Programming Cookbook

3.3 (3)
By: Aanand Shekhar Roy , Rashi Karanpuria

Overview of this book

The Android team has announced first-class support for Kotlin 1.1. This acts as an added boost to the language and more and more developers are now looking at Kotlin for their application development. This recipe-based book will be your guide to learning the Kotlin programming language. The recipes in this book build from simple language concepts to more complex applications of the language. After the fundamentals of the language, you will learn how to apply the object-oriented programming features of Kotlin 1.1. Programming with Lambdas will show you how to use the functional power of Kotlin. This book has recipes that will get you started with Android programming with Kotlin 1.1, providing quick solutions to common problems encountered during Android app development. You will also be taken through recipes that will teach you microservice and concurrent programming with Kotlin. Going forward, you will learn to test and secure your applications with Kotlin. Finally, this book supplies recipes that will help you migrate your Java code to Kotlin and will help ensure that it's interoperable with Java.
Table of Contents (16 chapters)
close
close

How to write an idiomatic logger in Kotlin

Kotlin has some great powerful features packed in it that we should be making use of to improve our code. This involves rethinking on our old best practices of coding. Many of our old coding practices can be replaced by better alternatives from Kotlin. One of them is how we write our logger. Though there are a lot of libraries out there that provide logging functionality, we will try to create our own logger in this recipe, just by using idiomatic Kotlin.

Getting ready

We will be using IntelliJ IDE to write and execute our code.

How to do it...

Let's go through the given steps to create an idiomatic logger in Kotlin:

  1. First, let's see how it was done in Java. In Java, SLF4J is used and considered de-facto, so much that logging seems like a solved problem in Java language. Here's what a Java implementation would look like:
private static final Logger logger = LoggerFactory.getLogger(CurrentClass.class);

logger.info(“Hi, {}”, name);
  1. It also works fine with Kotlin, obviously with minor modifications:
val logger = LoggerFactory.getLogger(CurrentClass::class)

logger.info(“Hi, {}”, name)

However, apart from this, we can utilize the power of Kotlin using Delegates for the logger. In this case, we will be creating the logger using the lazy keyword. This way, we will create the object only when we access it. Delegates are a great way to postpone object creation until we use it. This improves startup time (which is much needed and appreciated in Android). So let us explore a method using lazy delegates in Kotlin:

  1. We'll use java.util.Logging internally, but this works for any Logging library of your choice. So let’s use the Kotlin’s lazy delegate to get our logger:
public fun <R : Any> R.logger(): Lazy<Logger> {
return lazy { Logger.getLogger(this.javaClass.name) }
}
  1. Now in our class, we can simply call the method to get our logger and use it:
class SomeClass {
companion object { val log by logger() }

fun do_something() {
log.info("Did Something")
}
}

When you run the code, you can see the following output:

Sep 25, 2017 10:49:00 PM packageA.SomeClass do_something
INFO: Did Something

So, as we can see in the output, we get the class name and method name too (if you are accessing logger inside a method).

How it works...

Here, one thing to note is that we have put our logger inside a companion object. The reason for this is quite straightforward because we want to have only one instance of logger per class.

Also, logger() returns a delegate object, which means that the object will be created on its first access and will return the same value (object) on subsequent accesses.

There's more...

Anko is an Android library that uses Kotlin and makes Android development easier with the help of extension functions. It provides Anko-logger, which you can use if you don’t want to write your own logger. It is included in anko-commons, which also has a lot of interesting things to make it worthwhile to include it in your Android projects that use Kotlin.

In Anko, a standard implementation of logger will look something like this:

class SomeActivity : Activity(), AnkoLogger {
private fun someMethod() {
info("London is the capital of Great Britain")
debug(5) // .toString() method will be executed
warn(null) // "null" will be printed
}
}

As you can see, you just need to implement AnkoLogger and you are done.

Each method has two versions: plain and lazy (inlined):

info("String " + "concatenation")
info { "String " + "concatenation" }

The lambda result will be calculated only if Log.isLoggable(tag, Log.INFO) is true.

See also

To know more about delegated properties, refer to the Working with delegated Properties recipe in Chapter 3Classes and Objects.

Visually different images
CONTINUE READING
83
Tech Concepts
36
Programming languages
73
Tech Tools
Icon Unlimited access to the largest independent learning library in tech of over 8,000 expert-authored tech books and videos.
Icon Innovative learning tools, including AI book assistants, code context explainers, and text-to-speech.
Icon 50+ new titles added per month and exclusive early access to books as they are being written.
Kotlin Programming Cookbook
notes
bookmark Notes and Bookmarks search Search in title playlist Add to playlist font-size Font size

Change the font size

margin-width Margin width

Change margin width

day-mode Day/Sepia/Night Modes

Change background colour

Close icon Search
Country selected

Close icon Your notes and bookmarks

Confirmation

Modal Close icon
claim successful

Buy this book with your credits?

Modal Close icon
Are you sure you want to buy this book with one of your credits?
Close
YES, BUY

Submit Your Feedback

Modal Close icon
Modal Close icon
Modal Close icon