Scala 简单函数返回类型不匹配错误

0 scala

我有一个向量列表。每个向量以 的形式表示一个范围Vector(Double,Double)。我想创建一个函数,给定一个输入数字,找到它包含在哪个向量中并返回该向量的索引。我不知道是否有更简单的方法来做到这一点,我是 Scala 的新手,但我的代码如下:

val vectors = #List of vectors ( List[scala.collection.immutable.IndexedSeq[Double]] )

def in_range(start: Double, end: Double, x : Double): Boolean = {(x>= start && x<end)}

def find_index(x:Double): Int = {
    for(i <- 0 to n){
     if( in_range(vectors(i)(0),vectors(i)(1),x)){ 
        return i
     }
}
Run Code Online (Sandbox Code Playgroud)

我收到以下错误:

<console>:28: error: type mismatch;
 found   : Unit
 required: Int
        for(i <- 0 to 10){
              ^
Run Code Online (Sandbox Code Playgroud)

Tim*_*Tim 5

如果for终止而不返回值,它将返回Unit而不是 required Int,因此会返回错误消息。

但是您应该查看find此类方法,而不是遍历集合的索引。例如

def find_index(x: Double): Int =
  vectors.indexWhere(v => in_range(v(0), v(1), x))
Run Code Online (Sandbox Code Playgroud)