Differences in "prose" and "dot notation" when calling a method with (explicit) implicit parameters

I am not a Scala expert, and I am confused by the syntax of invoking a method with an implicit parameter.

Here is my situation:

I have a Spark RDD:

val myData: RDD[Array[String]] = ... 

and determined the order for him:

 object MyOrdering extends Ordering[Array[String]] = ... 

I want to filter out this RDD and take the top n entries in the RDD according to my order. Spark RDD has a method for receiving the first n records with this signature:

 def top(num: Int)(implicit ord: Ordering[T]): Array[T] 

I originally tried this code

 myData filter { D => D(9) == "yes" } top(50)(MyOrdering) 

What fails with this error:

 error: Int(50) does not take parameters } top(50)(MyOrdering) 

However, this code works:

 myData.filter(D => D(9) == "yes").top(50)(MyOrdering) 

To my beginner, an example of failed code and a sample of working code look like indicating equivalent logic. Am I wrong here? Am I really doing something different in two code examples? Or is it a problem with how the Scala compiler parses the code?

+5
source share
1 answer

You can replace the dot . a space for calling the method when the method has the value arity-1 (1 parameter list) or arity-0 (no parameter lists). For example, this does not compile:

 class Foo { def baz(x: Int)(y: Int) = this def qux(x: Int) = this } (new Foo) baz(1)(1) //Does not compile (new Foo).baz(1)(1) //Allowed (new Foo) qux(1) //Allowed, since qux is arity-1 (new Foo).qux(1) //Also allowed, of course 

When the last parameter list is implicit , the compiler can process the method using parameter lists n , as if it had arity n-1 , if the method is called with an implicit argument:

 class Foo { def baz(x: Int)(implicit y: Int) = this } implicit val y: Int = 1 (new Foo) baz(1) //Allowed (new Foo).baz(1) //Also fine (new Foo) baz(1)(2) //Still not allowed (new Foo).baz(1)(2) //Still allowed 

See the style guide for more details on method invocation rules.

+1
source

Source: https://habr.com/ru/post/1212833/


All Articles