The following Kotlin code attempts to define a generic function to find the element with the maximum length (for strings). What is wrong with this approach, and how can you fix it?

Android interview question for Advanced practice.

Answer

The length property is not defined for all types T; it only works for Strings. A type constraint is needed.

Explanation

The main problem is that the length property is only defined for strings, not all types T. Attempting to access it.length on a non-string element will result in a compile-time error. To fix this, we need to constrain T to be String: kotlin fun findLongestString(list: List<String): String? { return list.maxByOrNull { it.length } } Now, the function is type-safe and will only accept lists of strings. The maxByOrNull() handles the null case if the list is empty.

Related Questions