j.ss
j.ss

Reputation: 53

Why is returning: kotlin.Unit

I cannot understand the reason for returning the result ef: kotlin.Unit instead of_data: {"ndata": "test text"} Tell me why I am getting ef: kotlin.Unit and how should I do to get_data: {"ndata": "test text"}?

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val buttonApi: Button = view.findViewById(R.id.api_test_id)
    buttonApi.setOnClickListener {
        val ef = fuelapi.fuelsend()
        println("ef: $ef")          // ef: kotlin.Unit
    }
}

fun fuelsend() {
    var data = ""
    val httpAsync = "http://10.0.2.2:3000/test"
        .httpGet()
        .responseString { req, res, result ->
            when (result) {
                is Result.Failure -> {
                    val ex = result.getException()
                    println("ex: $ex")
                    data = "err: $ex"
                }
                is Result.Success -> {
                    data = result.get()
                    println("_data: $data")     // _data: {"ndata":"test text"}
                }
            }
        }

    httpAsync.join()
}

Upvotes: 0

Views: 1554

Answers (1)

sidgate
sidgate

Reputation: 15234

Your function fuelsend isn't returning anything. Kotlin function by default returns Unit. You need to specify the return type of the function, and return some value from the function body

fun fuelsend(): String {
    var data = ""
    val httpAsync = "http://10.0.2.2:3000/test"
        .httpGet()
        .responseString { req, res, result ->
            when (result) {
                is Result.Failure -> {
                    val ex = result.getException()
                    println("ex: $ex")
                    data = "err: $ex"
                }
                is Result.Success -> {
                    data = result.get()
                    println("_data: $data")     // _data: {"ndata":"test text"}
                }
            }
        }

    httpAsync.join()
    return data 
}

Upvotes: 4

Related Questions