This question already has answers here:
Scala foreach strange behaviour
(5 answers)
Closed 7 years ago.
Given these case classes:
case class FeatureDistance(id: Long, distance: Double)
case class SearchResult(score: Float, id: Long)
Why does this not compile?
val distances = List[FeatureDistance](FeatureDistance(1L, 10f))
val results = distances.map(SearchResult(0f, _.id))
But this does:
val results = distances.map(fd => SearchResult(0f, fd.id))
The compilation error says: missing parameter type for expanded function ((x$3) => x$3.id)
Is it because _ is only scoped to the map function so it's not visible in the SearchResult.apply call?
After doing a bit of research, I found a post on the old scala forums that contains this quote:
When you use "_" as a place holder for an anonymous parameter of a function, the scope of that function is the innermost parenthesis containing it.
So, it's just a question of scope. I suspect this has to do with problems that could otherwise result from having nested function calls that use more than one underscore. For instance:
//suppose we have some x:List[List[Int]]
x.map(_.map(_ + 1))
Related
This question already has answers here:
What is the apply function in Scala?
(7 answers)
Closed 1 year ago.
I have below "apply" function, what does apply function do? can you please explain for me?
def apply[K,V](m1:Map[K,V], m2:Map[K,V], merge: (V,V) => V): Map[K,V] =
combine(m1,m2,merge)
The apply function in companion objects and classes has a special meaning in that if an object/class is instantiated without specifying the function, it is the one which is run.
E.g.
object DDF { def apply(text :String) = println(s"got $text") }
DDF("text") // object called like function. function actually called is apply(String) here.
In your example, the apply function merely calls combine. so X(a,b,c) is the same as X.combine(a,b,c).
The technique is how we have achieve multiple constructors on classes too.
This question already has answers here:
What does => and () => mean in Scala [duplicate]
(5 answers)
Closed 6 years ago.
While looking at an open source code I found out that sometimes some people use syntax like this:
Seq[Date => String]
Can you please explain what does this mean and how it is used? I am new to Scala.
Seq[Date => String]
Is a sequence of functions from Date (taking in a parameter of type Date) to String (returning a String). It is syntactic sugar for Function1[Date, String]:
Seq[Function1[Date, String]]
For example, one could use:
val x = List[Date => String](date => date.toString)
Which, when invoked, would print the toString method of the Date class.
It means this is a sequence of Functions from Date to String. In Scala, functions are first-class citizens, which means (among other things) that functions have types. A => B is the notation describing the type of a function that takes an argument of type A and returns a value of type B.
For example, you can write:
val f1: Date => String = d => d.toString
def f2(d: Date): String = d.toString
val s: Seq[Date => String] = Seq(f1, f2)
This question already has answers here:
Error with varargs for function-objects in Scala?
(2 answers)
Closed 7 years ago.
I am quite new to Scala (and Spark, if this is somehow Spark-specific), so please forgive the super simple question.
To me, it seems like this code should compile just fine:
sqlContext.udf.register("json_extract_string", (rawJson: String, keyPath: String*) => {
[String]UDFs.jsonExtract(rawJson, keyPath:_*)
})
Yet compiling gives the error:
Error:(31, 89) ')' expected but identifier found.
sqlContext.udf.register("json_extract_string", (rawJson: String, keyPath: String*) => {
^
Why is this?
The function being called looks like this:
object UDFs {
def jsonExtract[T: Manifest](rawJson: String, keyPath: String*): Option[T] = {
implicit val formats = DefaultFormats
val json = parse(rawJson)
keyPath.foldLeft(json)(_ \ _).extractOpt[T]
}
}
In scala it is not permitted for anonymous functions to have variable length arguments, see this answer Scala: How do I define an anonymous function with a variable argument list?
There is a shorter form of what you're trying to express which should work:
sqlContext.udf.register("json_extract_string", UDFs.jsonExtract[String]_)
This:
[String]UDFs.jsonExtract(rawJson, keyPath:_*)
is not valid Scala.
If you need to cast, you have to explicitly call asInstanceOf:
UDFs.jsonExtract(rawJson, keyPath:_*).asInstanceOf[String]
But typically such casting is a code smell and a sign that you've gone down the wrong path.
This question already has an answer here:
using variable length argument in scala
(1 answer)
Closed 7 years ago.
I have an interface
object Leaf {
def apply(keys: Int*): Leaf = {
new Leaf(keys)
}
}
where Leaf class is defined as follows:
class Leaf(keys: Seq[Int]) extends Node(true, keys, Seq())
Is this possible to pass a Sequence as a keys parameter? Of course I could create second varargs method, but i wonder if there is a method which converts a Sequence into varargs paremeter.
Yes, and I think you mean varargs not varchar :)
Leaf(sequence: _*)
This question already has answers here:
What are the precise rules for when you can omit parenthesis, dots, braces, = (functions), etc.?
(6 answers)
Closed 9 years ago.
To my beginner's knowledge of Scala there isn't any way to achieve the last line. I hope I am mistaken, and I just wanted to confirm. Also, I don't understand why, because the compiler should know the owner object of the f method from the import statement.
object A { def f(s: Any) = println(s) }
import A.f
A f 1 //Works
f 2 // Does not compile
For clarification there are two questions:
How should a single parameter method without parenthesis and explicit owner object reference be called? (See the subject.)
What is the reason the compiler cannot understand the last statement?
object A { def f(s: Any) {println(s)} }
import A.f
A f 1 //works
f(2) // works
What are the precise rules for when you can omit parenthesis, dots, braces, = (functions), etc.?