Book Image

Programming Kotlin

Book Image

Programming Kotlin

Overview of this book

Quickly learn the fundamentals of the Kotlin language and see it in action on the web. Easy to follow and covering the full set of programming features, this book will get you fluent in Kotlin for Android.
Table of Contents (20 chapters)
Programming Kotlin
Credits
About the Authors
About the Reviewers
www.PacktPub.com
Customer Feedback
Preface

toString out of the box


When you define a new type, best practices dictate that you should provide an override for the toString method. This method should return a string describing the instance. Let's consider the BlogEntry class we defined at the beginning of this chapter. There is quite a bit of typing you will have to do to implement this method. But why do it when you can get it out of the box? Let the compiler do it for you. If you add or remove a new field, it will automatically update the code for you. The likelihood of you leaving out the change to the toString code body when a field is added/renamed/removed is quite high:

public java.lang.String toString();
Code:
0: new           #122                // class  java/lang/StringBuilder
3: dup        
4: invokespecial #123              // Method  java/lang/StringBuilder."<init>":()V
7: ldc           #125                // String BlogEntry(title=
9: invokevirtual #129                // Method  java/lang/StringBuilder.append:(Ljava...