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

Scala Anorm查询返回List[Unit]与List[String]类型不匹配求助

Scala Anorm查询返回List[String]时出现类型不匹配错误

编译错误信息:

type mismatch;
found : List[Unit]
required: List[String]

错误原因

你的辅助函数中,map闭包内最后一行是赋值语句val conceptName = conceptRecord[String]("concept_name").toString,Scala里赋值语句的返回值是Unit,因此整个map操作生成的是List[Unit],和函数声明的返回类型List[String]不匹配,导致编译失败。

另外,conceptRecord[String]("concept_name")本身已经是String类型,不需要额外调用toString。

修正后的代码

def getActiveConceptNames(organizationId : Long) : List[String] = {
  DB.withConnection { implicit c =>
    // 优化SQL:只查询需要的concept_name字段,避免不必要的数据读取
    val conceptQuery = SQL("select concept_name from tbl_concepts where org_id = {org_id} and is_deleted = 0;")
      .on("org_id" -> organizationId)
    conceptQuery().map { conceptRecord =>
      // 直接返回String类型的字段值,map会将每个元素转换为String,最终生成List[String]
      conceptRecord[String]("concept_name")
    }.toList
  }
}

如果需要保留变量赋值的写法,确保闭包最后一行返回该变量:

conceptQuery().map { conceptRecord =>
  val conceptName = conceptRecord[String]("concept_name")
  conceptName // 显式返回变量,确保map的元素类型是String
}.toList

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 00:24:18