CodeBlanks Logo Icon CodeBlanks

Module design

Design the skeleton of the helper library class.

Project: Helper library

In this five-lesson project you will build a helper library. Each lesson adds one piece, and by the final lesson you will have a library that brings all helpers together.

You will use what you learned in previous groups: object for singletons and extension functions to add methods to existing types. Throughout the project you will define the Helpers object and extension functions for String, Int and LocalDate. In the first lesson you will create the skeleton of the Helpers object: a greet method and a main call.

The Helpers object skeleton

The first lesson defines an object named Helpers. In Kotlin object declares a singleton; you access it directly through its name.

Example skeleton: object Helpers { fun greet(name: String): String { return "Hello, $name!" } }. This object is called as Helpers.greet("Alex"). Methods inside an object need no instance; they are called directly through the object name. In the next lessons you will add extension functions alongside this object.

Practice Define the Helpers object

Define an object named Helpers. Add a fun greet(name: String): String method whose body returns "Hello, $name!". In main print the result of Helpers.greet("Alex") with println.

Starter code

Main.kt
// Define the Helpers object
// greet method: returns Hello, {name}!
// call greet in main and print

Sample solution

Main.kt
object Helpers {
    fun greet(name: String): String {
        return "Hello, $name!"
    }
}

fun main() {
    println(Helpers.greet("Alex"))
}

Expected output

Hello, Alex!

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Which structure is defined in the first lesson of the helper library project?

  • LocalDate extension
  • String extension
  • Int extension
  • Helpers object Correct answer

Explanation: The first lesson creates the skeleton of the Helpers object.

2 Complete the object definition

Question
object ____ {
    fun greet(name: String): String {
        return "Hello, $name!"
    }
}
Answer
object Helpers {
    fun greet(name: String): String {
        return "Hello, $name!"
    }
}

Explanation: object Helpers declares a singleton.

3 Match the Helpers parts

Term Meaning
object Helpers Singleton declaration
fun greet(name) Method
Helpers.greet(...) Call
return "Hello, $name!" Return value

All lessons in Intermediate