2

Passing function literal with underscore as an argument to map chained with toSet on another collection (e.g. List) results in type error:

scala> List(1, 2, 3).toSet map (_.toString)
<console>:12: error: missing parameter type for expanded function ((x$1) => x$1.toString)
   List(1, 2, 3).toSet map (_.toString)

However, when Set produced in the same manner is assigned to a value, subsequent invocation of map works as expected:

scala> val set = List(1, 2, 3).toSet
set: scala.collection.immutable.Set[Int] = Set(1, 2, 3)

scala> set map (_.toString)
res1: scala.collection.immutable.Set[String] = Set(1, 2, 3)

Back to chaining, when constructor is used to produce Set from another collection (e.g. List) it works as expected:

scala> Set(List(1, 2, 3):_*) map (_.toString)
res1: scala.collection.immutable.Set[String] = Set(1, 2, 3)

Is this a bug in Scala compiler or is there something else that I'm missing?

kirlich
  • 7,998
  • 2
  • 19
  • 10
  • Also a newbie here, but `List(1, 2, 3).toSet.map((x: Int) => x.toString)` seems to work. – Psidom Dec 10 '16 at 04:15
  • @Psidom Yes, as suggested by compiler adding parameter type in function literal will help compiler and avoid type error. However, the question is focused on the issue when using 'function literal with underscore' and the inconsistency when compiler has issues with it: only has problem when invocations are chained. – kirlich Dec 10 '16 at 08:52
  • strangely, this works: `List(1, 2, 3).to[immutable.Set].asInstanceOf[Set[Int]].map(_.toString)` (taken from `toSet` implementation of `TraversableOnce` – Raphael Roth Dec 10 '16 at 13:12

0 Answers0