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

Kotlin Lambda函数代码返回Function1而非预期Int 10问题求助

问题排查与解决

问题原因

你的代码里Bird.companion.a函数的返回类型是(Int) -> Int,这是一个函数类型。调用Bird.a { 10 }得到的是一个函数对象,而非Int值。直接打印这个函数对象时,Kotlin会输出它的类型标识Function1<java.lang.Integer, java.lang.Integer>,这就是你看到的奇怪字符串。

解决方案

根据你的实际需求,有两种修改方式:

方式1:让a直接返回Int值

如果你的初衷是让a函数返回Int类型的10,直接修改a的返回类型,并返回b()的执行结果:

fun main(args: Array<String>) {
    println(Bird.a { 10 }) // 现在会输出10
}

class Bird() {
    companion object {
        fun a(b: @JvmSuppressWildcards () -> Int): Int {
            return b()
        }
    }
}

方式2:保留函数返回类型,但执行后再打印

如果a函数确实需要返回(Int) -> Int类型的函数,那你需要调用这个返回的函数(随便传一个Int参数即可,因为你的lambda里没用到这个参数),再打印结果:

fun main(args: Array<String>) {
    // 调用返回的函数,传入任意Int参数(比如0),再打印结果
    println(Bird.a { 10 }(0)) // 输出10
}

class Bird() {
    companion object {
        fun a(b: @JvmSuppressWildcards () -> Int): (Int) -> Int {
            return { b() }
        }
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.11 02:25:29