You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何出现kotlin.Unit输出?如何解决该Kotlin编程问题

Kotlin函数调用输出kotlin.Unit问题解决

我编写了如下Kotlin代码:

package com.example.codingisfun

fun main(){
    val phone1= MobilePhone("Android","Samsung","S30")
    val phone2= MobilePhone("IOS","Apple","Iphone 14")
}

class MobilePhone(osName: String, brand: String, model: String){
    private var battery= 30
    init {
        println("The phone $model from $brand uses $osName as its Operating System")
        println(chargeBattery(30))
        println(battery)
    }
    private fun chargeBattery(charged:Int){
        println("before charge:$battery,charged: $charged and now: ${battery+charged}")
        battery += charged
    }
}

运行后输出内容为:

The phone S30 from Samsung uses Android as its Operating System
before charge:30,charged: 30 and now: 60
kotlin.Unit
60
The phone Iphone 14 from Apple uses IOS as its Operating System
before charge:30,charged: 30 and now: 60
kotlin.Unit
60

我曾尝试调整chargeBattery的调用方式,但依旧会输出kotlin.Unit,请问如何解决这个问题?


问题原因

你看到的kotlin.Unit是因为chargeBattery函数没有返回值(Kotlin中无返回值的函数默认返回Unit类型),而你在init块里调用println(chargeBattery(30)),相当于把这个函数的返回值(也就是Unit)打印出来了。

解决方案

直接调用chargeBattery(30)即可,不需要把它放在println里面:

修改后的init代码块:

init {
    println("The phone $model from $brand uses $osName as its Operating System")
    chargeBattery(30) // 直接调用,不用包裹在println里
    println(battery)
}

修改后运行输出会变成:

The phone S30 from Samsung uses Android as its Operating System
before charge:30,charged: 30 and now: 60
60
The phone Iphone 14 from Apple uses IOS as its Operating System
before charge:30,charged: 30 and now: 60
60

这样就不会出现多余的kotlin.Unit输出了。

内容的提问来源于stack exchange,提问作者raptured_kira

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 12:40:11