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.
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.
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]:
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With