Menu
Coddy logo textTech

Recap - Safe Access

Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 18 of 93.

challenge icon

Challenge

Easy

Write a function safeWordInfo that takes word1 and word2 and returns a formatted string with information about both words.

The function receives two strings that may represent actual words or the literal string "null" to indicate a missing value. You need to handle these as nullable values and use safe access operators to build the result.

Logic:

  1. Treat any input equal to "null" as a null value
  2. For each word, get its length using safe call. If null, use 0 as the default length
  3. For each word, get its uppercase version using safe call. If null, use "N/A" as the default

Parameters:

  • word1 (String): First word, or "null" if missing
  • word2 (String): Second word, or "null" if missing

Returns: A string in the format: Word1: [UPPERCASE] ([length]) | Word2: [UPPERCASE] ([length])

Example: For inputs "hello" and "null", return "Word1: HELLO (5) | Word2: N/A (0)"

The two conversion lines in the starter are provided for you. Keep them unchanged; you will learn their conditional syntax later. Your work starts with the nullable values w1 and w2.

Try it yourself

fun safeWordInfo(word1: String, word2: String): String {
    // Provided conversion: leave these two lines unchanged.
    val w1: String? = if (word1 == "null") null else word1
    val w2: String? = if (word2 == "null") null else word2
    // Use safe calls and fallbacks to build and return the result.
    TODO("Complete the safe access operations")
}

All lessons in Fundamentals

Practice on your own: Kotlin playground