Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scala error: found and required are same

Tags:

scala

Following code is from my REPL:

scala> words.zipWithIndex.filter((x:java.lang.String,index:Int)=>index%2==0)
<console>:9: error: type mismatch;
found : (java.lang.String, Int) => Boolean
required: (java.lang.String, Int) => Boolean
words.zipWithIndex.filter((x:java.lang.String,index:Int)=>index%2==0)

Here found and required are the same. Could anyone help me understand the problem.

like image 403
hrishikeshp19 Avatar asked Jan 21 '12 09:01

hrishikeshp19


People also ask

How do you check for exceptions in Scala?

However, Scala doesn't actually have checked exceptions. When you want to handle exceptions, you use a try {...}catch {...} block like you would in Java except that the catch block uses matching to identify and handle the exceptions. Throwing an exception looks the same as in Java.

How do you handle errors in Scala?

We already demonstrated one of the techniques to handle errors in Scala: The trio of classes named Option, Some, and None. Instead of writing a method like toInt to throw an exception or return a null value, you declare that the method returns an Option, in this case an Option [Int]:

What is the Scala equivalent of object?

You're missing types all over the place, but it's kind of incidental to the puzzle. Any is the Scala equivalent of Object. Pretend you're trying to diagnose an inheritance problem and it'll probably make sense. I think i found a better way to write it actually.

What is the difference between assert and ensuring in Scala?

These functions come in Predef.scala package and one does not have to import any separate package. Ensuring – is a post condition that has also been covered. Assert method puts a necessity for a condition to be satisfied while performing a certain action. If this condition is satisfied, then the code works fine, otherwise it throws an exception.


1 Answers

They are not really the same -- that's just a badly formatted error message. Scala 2.10 will have a better error message.

Basically, one is a tuple while the other is a two-parameters argument list. Specifically:

words.zipWithIndex // Creates a tuple

(x: String, index: Int) => index % 2 == 0 // is a function with two parameters

You can fix it in two ways:

filter((t: (String, Index)) => t._2 % 2 == 0) // use a tuple as parameter
filter { case (x: String, index: Int) => index % 2 == 0 } // use pattern matching
like image 116
Daniel C. Sobral Avatar answered Nov 16 '22 00:11

Daniel C. Sobral