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

Scala函数报错‘type mismatch; found : Unit required: Int’的原因?

Scala类型不匹配错误解决:Unit required: Int

错误原因

你定义的get_end函数声明返回Int类型,但当前代码仅在循环内满足if条件时才会返回Int值。如果遍历完所有元素都未触发条件分支的return,函数将没有明确返回值,Scala会默认返回Unit(类似Java的void),这与函数声明的返回类型冲突,导致类型不匹配错误。

修复方案

给函数添加一个明确的默认返回值,确保无论是否触发条件分支,函数都能返回Int类型的值。以下是修复后的代码:

val sdf: SimpleDateFormat = new SimpleDateFormat("yyyyMMddHHmm");
val cal: Calendar = Calendar.getInstance();

def get_end(event_end_dtm : ListBuffer[String], window_start: String, window_stop: String): Int = {
  val startIndex = event_end_dtm.indexOf(window_start)
  
  for (i <- startIndex until event_end_dtm.length){
    if(sdf.parse(event_end_dtm(i)).compareTo(sdf.parse(window_stop)) > 0){
      println( "Value of i: " + i )         
      return i-1
    } 
  }
  
  // 默认返回值:这里假设返回列表最后一个元素的索引,可根据业务需求调整
  event_end_dtm.length - 1
}

函数式风格优化(可选)

Scala推荐使用函数式编程范式,避免var和return,可以用indexWhere简化逻辑,让代码更简洁易读:

import java.text.SimpleDateFormat
import java.util.Calendar
import scala.collection.mutable.ListBuffer

val sdf: SimpleDateFormat = new SimpleDateFormat("yyyyMMddHHmm");
val cal: Calendar = Calendar.getInstance();

def get_end(event_end_dtm : ListBuffer[String], window_start: String, window_stop: String): Int = {
  val startIndex = event_end_dtm.indexOf(window_start)
  val stopDate = sdf.parse(window_stop)
  
  // 从startIndex开始查找第一个大于stopDate的元素索引
  val targetIndex = event_end_dtm.indexWhere(
    dateStr => sdf.parse(dateStr).compareTo(stopDate) > 0, 
    startIndex
  )
  
  targetIndex match {
    case -1 => event_end_dtm.length - 1 // 未找到匹配元素时的默认返回值
    case idx => 
      println(s"Value of i: $idx")
      idx - 1
  }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 15:30:52