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

Scala函数类型不匹配问题求助:返回String与null报错原因

Scala类型不匹配问题分析:Required: Null, Found: String

问题代码

def isLarger(inputNum: Int) = {
    var res = null
    if (inputNum.>(10)) {
        res = "aaa"
      }
    res
}

报错原因

Scala编译器会根据变量初始值自动推断类型:

  • 当你写var res = null时,编译器会把res的类型推断为Null类型,而Null类型只能接受null值,无法容纳其他引用类型(比如String)。
  • 后续给res赋值字符串"aaa"时,String类型和已推断的Null类型不兼容,因此触发类型不匹配错误。

解决方案

显式指定变量res的类型为String(String作为引用类型,可以接受null值):

def isLarger(inputNum: Int) = {
    var res: String = null
    if (inputNum > 10) {
        res = "aaa"
    }
    res
}

更简洁的写法(直接用表达式替代变量):

def isLarger(inputNum: Int): String = if (inputNum > 10) "aaa" else null

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 12:45:46