Reputation: 29
Just started with Scala. Everytime I try to execute it, a mismatch error is shown. I'm returning integer only. Still the compiler finds type Unit
from god knows where.
object a {
def search(e : Int,arr : Array[Int]): Int = {
var l: Int = 0
for(l <- 0 arr.length) {
if(arr(l) == e) {
return e
} else {
return -1
}
}
}
def main(args: Array[String]) {
var i = 0
println("enter the number of elements ")
var n = readLine.toInt
println("enter the elements are")
var arr = new Array[Int](n)
for(i <- 0 to n-1) {
println("enter element "+i+" ")
arr(i) = readLine.toInt
}
for(i <- 0 to n-1) {
println("element "+i+" is "+arr(i))
}
println("sorted array is")
arr = arr.sortWith(_ < _)
for(i <- 0 to n-1) {
println(arr(i))
}
println("enter the number to be searched ")
var e = readLine.toInt
var result: Int = search(e,arr)
if(result == e) {
println("element found")
} else {
println("element not found")
}
}
}
output
yudhveer@lfc:~$ scalac a.scala
a.scala:6: error: type mismatch;
found : Unit
required: Int
for(l<-0 until arr.length)
^
one error found
Upvotes: 1
Views: 1026
Reputation: 20415
More scalish approaches to search
as originally defined above, which benefits from functional immutability and Scala idiomatic elements. Note array inclusion conveys the intended semantics,
def search(e : Int, arr : Array[Int]): Int = if (arr contains e) e else -1
Using a for comprehension we yield found elements and test for non emptiness in the resulting list,
def search(e : Int, arr : Array[Int]): Int = {
val res = for (a <- arr if a == e) yield a
if (res.nonEmpty) res.head else -1
}
Relevant here is that we iterate over each element of arr
without having to use indexing. Also consider exists
which will halt on first match encountered,
def search(e : Int, arr : Array[Int]): Int = if (arr.exists( _ == e)) e else -1
Using find
we deliver the found value or else -1
,
def search(e : Int, arr : Array[Int]): Int = arr.find(_ == e).getOrElse(-1)
Note that find
returns an Option
, either Some(value)
or None
if none were found; with getOrElse
we handle the not found case.
Upvotes: 0
Reputation: 10894
The basic cause of the error is in the for
, you forget the yield
.
On a larger scale you run in a classical transition problem from Java to Scala. You can not break a for loop. (In reality you can but only in a hacky way: How to yield a single element from for loop in scala?).
A possible approach here is to make use of the great Scala Collection Library whcih allready contains the function you implemented: indexOf
:
def search(e : Int,arr : Array[Int]) : Int = arr.indexOf(e)
Will give the expected result.
Upvotes: 2