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?): Unit{
var b: String? = s1
val l = b?.length ?: -1
--- End ---

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

We now getting error as -

Solution.kt:37:8: error: type mismatch: inferred type is Int but Unit was expected
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)

In your example, you have set your function return type to Unit, which means (approximately) return void.

You have to switch function contract to return an integer :

fun nullable(input: String?) : Int = input?.length ?: -1

Well, at this point, you have to look closely at the lines of your function to understand what each statement does and why is it needed. I can already say to you there’s a problematic variable assignment in it.

thanks issue resolved… working code is -

fun nullable(s1: String?): Int{
var b: String? = s1
val l = if (b != null) return b.length else return -1

Great. But this would definitely not pass review:

  • It is doing a few silly things.
  • The code can be way shorter.

Hint: look into what you can do with question marks.