Kotline Null safety

We need to create function named as nullable which will accept nullable string as a parameter. Return length of the string , if NULL then -1ā€¦ task as per it written code

import java.io.*
import java.math.*
import java.security.*
import java.text.*
import java.util.*
import java.util.concurrent.*
import java.util.function.*
import java.util.regex.*
import java.util.stream.*
import kotlin.collections.*
import kotlin.comparisons.*
import kotlin.io.*
import kotlin.jvm.*
import kotlin.jvm.functions.*
import kotlin.jvm.internal.*
import kotlin.ranges.*
import kotlin.sequences.*
import kotlin.text.*

--- Editable code as ---
fun nullable(s1: String): Units{
 var b: String? = s1
b=null
val l = b?.length ?: -1
print(l)
return(l)
  }
--- End ---

fun main(args: Array<String>) {
    val str = readLine()!!
        var result=-100
    if(str=="null"){
         result = nullable(null)
    }else
        result = nullable(str)
    println(result)
}

We getting error as

  • Solution.kt:22:27: error: unresolved reference: Units fun nullable(s1: String): Units{ ^

  • Solution.kt:34:28: error: null can not be a value of a non-null type String result = nullable(null) ^

Thanks for the question, @ashishsmse14 !

Instead of:

fun nullable(s1: String): Units{

Use:

fun nullable(s1: String?): Unit{

There are two differences here:

  1. Use Unit without the ā€œsā€ at the end. You could also optionally omit : Unit as it it the default return type for the function.
  2. Use String? with a ā€œ?ā€ for the parameter type. This makes the parameter nullable.

I hope this helps! Please let us know if you have any questions about the book.

1 Like

thanks -

fun nullable(s1: String?): Unit{
var b: String? = s1
b=null
val l = b?.length ?: -1
print(l)
return(l)
}

We now getting error as -

Solution.kt:37:8: error: type mismatch: inferred type is Int but Unit was expected
return(l)
       ^
Solution.kt:44:19: error: type mismatch: inferred type is Unit but Int was expected
         result = nullable(null)
                  ^
Solution.kt:46:18: error: type mismatch: inferred type is Unit but Int was expected
        result = nullable(str)

issue resolved thanks

1 Like

Iā€™m glad your issue is resolved! Thanks for reaching out.