scala - Why do one of these split & filter work but not the other? -
val c = s.split(" ").filter(_.startswith("#")).filter(x => x.contains("worcester") || x.contains("energy"))
works
but not
val c = s.split(" ").filter(_.startswith("#")).filter(_.contains("worcester") || _.contains("energy"))
i have not understood why latter not work - may have flaw in fundamentals
any appreciated sumit
using underscore known placeholder syntax. so, _.contains("x")
equivalent x => x.contains("x")
. can use each parameter once when using placeholder syntax. using multiple placeholders denotes multiple parameters of anonymous function (which used in order of underscores). so, when write:
o.filter(_.contains("worcester") || _.contains("energy"))
it theoretically equivalent to
o.filter((x, y) => x.contains("worcester") || y.contains("energy"))
which doesn't type check, since filter
expects parameter of type array[string] => boolean
.
multiple placeholders common when using reduce
variants. example, factorial can computed (1 n).reduce(_ * _)
. works because reduce
expects parameter of type (int, int) => int
, _ * _
, equivalent (x, y) => x * y
fits expected type.
it's important note placeholder syntax applies smallest possible scope. so, example, f(g(_))
equivalent f(x => g(x))
, , not x => f(g(x))
, common mistake.
you can find comprehensive list of use of underscore in scala here, , little bit more placeholder syntax here.