简体   繁体   中英

In my scala function, why am I getting error - "type mismatch; found : Unit required: Int"?

Here is the definition of my code:

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 = {
      var i = 0;
      
      for (i <- event_end_dtm.indexOf(window_start) 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
        } 
        
      }
     
    }

When I am trying to run the code I am getting the below error:

type mismatch; found : Unit required: Int

I am very new to scala, hence if someone can please provide some help on this one, will really appreciate that.

get_end doesn't return anything explicitly if the if never triggers. You need to decide what you want to do in that case. Most commonly, you'd return an Option .

def get_end(event_end_dtm : ListBuffer[String], window_start: String, window_stop: String): Option[Int] = {
  var i = 0;
  for (i <- event_end_dtm.indexOf(window_start) until event_end_dtm.length){
    if(sdf.parse(event_end_dtm(i)).compareTo(sdf.parse(window_stop)) > 0){
      println( "Value of i: " + i )         
      return Some(i-1)
    } 
  }
  // Oops, didn't find it; return nothing
  None
}

If you're quite certain the value should exist, you can always explicitly throw an exception after the fact, instead. But this is generally a less favorable approach than letting the caller decide what to do.

def get_end(event_end_dtm : ListBuffer[String], window_start: String, window_stop: String): Int = {
  var i = 0;
  for (i <- event_end_dtm.indexOf(window_start) 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
    } 
  }
  // Oops, didn't find it; commence panicking
  throw new RuntimeError("Couldn't find the value! :(")
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM