Recap - Safe Access
Part of the Fundamentals section of Coddy's Kotlin journey. Lesson 18 of 93.
Challenge
EasyWrite 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:
- Treat any input equal to
"null"as a null value - For each word, get its length using safe call. If null, use
0as the default length - 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 missingword2(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
4Operators Part 1
Arithmetic OperatorsModulo OperatorAugmented AssignmentComparison OperatorsRecap - Simple Math7Basic IO
Println FunctionString TemplatesReadLine InputType ConversionRecap - Years Until RetirementRecap - True or False10Functions
Declare A FunctionParameters And ArgumentsReturn ValuesNamed ArgumentsDefault ValuesSingle Expression FunctionsRecap - Sigma FunctionRecap - Validation Function2Variables
Val vs VarType InferenceNumbersStringBooleanNaming ConventionsRecap - Initialize Variables5Operators Part 2
Logical Operators Part 1Logical Operators Part 2Logical Operators Part 3Ternary With If ExpressionRecap - Simple Logic8Bill Split Calculator
Welcome MessageGetting Input3Nullability
What Is Null SafetyNullable TypesSafe Call OperatorElvis OperatorFunction Challenge BasicsNot Null AssertionRecap - Safe Access6Decision Making
If StatementIf - ElseIf As An ExpressionWhen ExpressionWhen With RangesRecap - Simple Calculator9Loops
For LoopWhile LoopDo-While LoopBreakContinueRanges In LoopsNested LoopRecap - FactorialRecap - Dynamic InputPractice on your own: Kotlin playground