0

The toPascalCase function is intended to convert strings containing spaces or - to Pascal case.

Below is my code ->

fun toPascalCase(str: String): String {
    lateinit var ans: String

    for(i in str) {
        if(i != ' ' && i != '-') {
            ans += i
        }
    }
    return ans
}

fun main() {

toPascalCase("Harsh kumar-singh")

} 

I have used the lateinit keyword before ans variable. In the for loop I have initialized the ans variable but still the compiler throws the following error ->

Exception in thread "main" kotlin.UninitializedPropertyAccessException: lateinit property ans has not 
been initialized
at FileKt.toPascalCase (File.kt:10) 
at FileKt.main (File.kt:18) 
at FileKt.main (File.kt:-1) 

Please help me with the code. Thank you

Yuseff
  • 169
  • 4
  • 14
  • "In the for loop I have initialized the ans variable". No, you haven't. `ans += i` is equivalent to `ans = ans + i`, which reads the value _before_ setting it. A `lateinit` var will hold `null` initially -- and you can't add that to anything, hence the error. (`lateinit` makes no sense for local variables; it's only for properties that can't be initialised until after their object is, which is a relatively rare situation. And even then, you still need to set a value before you use it.) – gidds Sep 11 '20 at 07:32

1 Answers1

0

Instead of lateinit var, you should use a simple var initializing it to an empty string.

fun toPascalCase(str: String): String {
    var ans = ""
    ...
fernandospr
  • 2,976
  • 2
  • 22
  • 43