2

given the following input:

scala> val as = List(Array(1,2,3), Array(10,20,30), Array(100,200,300))
as: List[Array[Int]] = List(Array(1, 2, 3), Array(10, 20, 30), Array(100, 200, 300))

I am wondering why this works:

EXAMPLE 1

scala> as.reduce((x,y) => x)
res65: Array[Int] = Array(1, 2, 3)

But this seemly identical thing does not work:

EXAMPLE 2

scala> as.reduce{case(x,y) => x}
<console>:13: error: missing parameter type for expanded function
The argument types of an anonymous function must be fully known. (SLS 8.5)
Expected type was: (?, ?) => ?
       as.reduce{case(x,y) => x}

Can anyone explain why the 1st example works but not the 2nd example?

anthonybell
  • 5,790
  • 7
  • 42
  • 60
  • Duplicate of: http://stackoverflow.com/a/12869583/1448212 – Richard Sitze Mar 15 '17 at 01:29
  • 4
    Possible duplicate of [The argument types of an anonymous function must be fully known. (SLS 8.5)](http://stackoverflow.com/questions/12869251/the-argument-types-of-an-anonymous-function-must-be-fully-known-sls-8-5) – Richard Sitze Mar 15 '17 at 01:29
  • 1
    I don't think this is a duplicate of that question. They both run into the same error, but this question is asking why these two specific examples are different. – Michael Zajac Mar 15 '17 at 04:06
  • The referenced answer talks about that point – Richard Sitze Mar 15 '17 at 13:50
  • This question (mentioned below) seems closest to my question: http://stackoverflow.com/questions/26240898/pattern-matching-on-function-parameters/26243303#26243303 – anthonybell Mar 15 '17 at 23:07

2 Answers2

2

As the error message said, you need to specify type Array[Int]. This one will work:

as.reduce[Array[Int]]{ case (x,y) => x}

There is a good explanation here.

Community
  • 1
  • 1
Shawn Xiong
  • 470
  • 3
  • 14
1

In Example 1, the argument to reduce is a Function2, taking two inputs (x and y) and returning x.

In Example 2, the argument to reduce is a Function1, taking one input, which happens to be a Tuple2, and returning the first element in the tuple.

The reduce method requires a Function2 as its argument, and so that's why Example 1 works, but Example 2 doesn't.

dhg
  • 52,383
  • 8
  • 123
  • 144