1

I have the following scala code:

val test = rows.groupBy(l => l(8))
val m = test.reduce((a, b) => if (a._2.size > b._2.size) a else b)
val mina = m._2.minBy(x => x(0));
val minv = mina(0);

I would like to write

val minv = m._2.minBy(x => x(0))(0);

but I get a compiler error

[error] D:\dev\local\spark\httpLogs\src\main\scala\Main.scala:35:38: type mismatch;
[error]  found   : Int(0)
[error]  required: Ordering[String]
[error]                                 val minv = m._2.minBy(x => x(0))(0);
[error]                                                                  ^

I also try

val minv = (m._2.minBy(x => x(0)))(0);

but just get another error.

Can this be written in one line ?

tschmit007
  • 7,559
  • 2
  • 35
  • 43

1 Answers1

2

Scala implicit parameters are neat, but if you don't know about them, they're confusing.

val mina = m._2.minBy(x => x(0))

is actually (resolved by implicit resolution)

val mina = m._2.minBy(x => x(0))(Ordering.String)

So when you're calling

val minv = m._2.minBy(x => x(0))(0)

You're actually passing the 0 as an explicit argument to the implicit.

By assigning the result to a variable, you're letting the compiler insert the implicit argument. If you're calling it directly, curried function arguments (the implicit is a curried argument after the explicit function) and syntax sugar for apply collide. And the compiler picks curried function arguments.

If you've got an object with an apply method on it, e.g. List:

val list = List(1, 2, 3)

it'll rewrite that to List.apply(1, 2, 3). That's why apply works in the above example, because it's telling the compiler to explicitly use the apply, instead of relying on the syntax sugar which gets overridden by the curried function.

More on implicits: Understanding implicit in Scala

Reactormonk
  • 21,472
  • 14
  • 74
  • 123