How to define a method in Scala that returns a Java object? - scala

I want to define a private method in scala singleton class that looks like;
private def createDomNode(tag: String, attrs: Map[String , String]): DomNode {
}
DomNode is Java type, not scala type. attrs is scala Map with both key and value being of type String.
But above gives error. What is the correct format?
Thanks Easy Angel for the answer. There is still some confusion. According to Programming in Scala book written by the inventor of the language, the below is a function:
def max(x: Int, y: Int): Int = {
if (x > y) x
else y
}
But your answer says it is method and not function. Can you kindly explain?
What is REPL?

You should just put =:
private def createDomNode(tag: String, attrs: Map[String , String]): DomNode = {
// ...
}
If you will not put = between method signature and body, then return type is Unit, so this:
def m(i: Int) {}
is the same as
def m(i: Int): Unit = {}
Response to the comment: What I described earlier is actually method, if you define it within object, class or trait definition. Function syntax would look like this:
val createDomNode: (String, Map[String , String]) => DomNode = { (tag, attrs) =>
// ...
}
As You can see I define val with name createDomNode of function type. It can also be written like:
val createDomNode: Function2[String, Map[String , String], DomNode] = { (tag, attrs) =>
// ...
}
here is another example. In this case I define method that generates new function each time you call it:
def createDomNode = (tag: String, attrs: Map[String , String]) => new DomNode
But it's important to understand, that method returns a "function that returns DomNode" in this case, but not DomNode itself.
About Programming in Scala reference. I think you are talking about Chapter 2 - Step 3 (in the intro)
As you can see max function is defined in REPL, and it's really function. Actually you can also write something like this:
class MyClass {
def myMethod(i: Int): Int = {
def myInnerFn(x: Int) = x * x
myInnerFn(i)
}
}
In this case myMethod is method and myInnerFn is function. So as you can see, it highly depends on the context. I believe this syntax for myInnerFn is just syntactic sugar for (I need to look in spec in order to say for sure):
val myInnerFn = (x: Int) => x * x
The same happens in REPL. And by the way that's because I wrote at the beginning:
if you define it within object, class or trait definition
Sorry, I need to be more clear about this and describe it in more detail in my second update.
I looked in Scala spec. Seems that I'm not totally correct when I say that myInnerFn is syntactic sugar for the function. but seems that it's called Method Type. You can find it in spec section 3.3.1 Method Type:
http://www.scala-lang.org/docu/files/ScalaReference.pdf
hope it will give you some clue, if you want to dive deeper in this. I think it's easy to get lost in terminology. You can function in 2 contexts. In first we have
Function - returns some value
Procedure - returns no value (or in Scala context it returns Unit)
And in second context:
Function - executable piece of code that can be passes around and treated as value
Method - belongs to the class
And it's sometimes not clear in what context it meant. For example I can tell you that myMethod is as function just because it has return value (or in other words: myMethod it's not procedure). I believe it's the same case in book.
One more thing. Sections 8.1, 8.2, 8.3 from Programming in Scala can help you to understand this terminology. And if I'm correct in my assumptions, what you think as Function is called First-class function in the book (it's described in section 8.3).
Hope this helps

Related

What's the purpose of Currying given other alternatives to return a function in Scala?

I'm currently doing a Scala course and recently I was introduced to different techniques of returning functions.
For example, given this function and method:
val simpleAddFunction = (x: Int, y: Int) => x + y
def simpleAddMethod(x: Int, y: Int) = x + y
I can return another function just doing this:
val add7_v1 = (x: Int) => simpleAddFunction(x, 7)
val add7_v2 = simpleAddFunction(_: Int, 7)
val add7_v3 = (x: Int) => simpleAddMethod(x, 7)
val add7_v4 = simpleAddMethod(_: Int, 7)
All the values add7_x accomplish the same thing, so, whats the purpose of Currying then?
Why I have to write def simpleCurryMethod(x: Int)(y: Int) = x + y if all of the above functions do a similar functionality?
That's it! I'm a newbie in functional programming and I don't know many use cases of Currying apart from saving time by reducing the use of parameters repeatedly. So, if someone could explain me the advantages of currying over the previous examples or in Currying in general I would be very grateful.
That's it, have a nice day!
In Scala 2 there are only four pragmatic reasons for currying METHODS (as far as I can recall, if someone has another valid use case then please let me know).
(and probably the principal reason to use it) to drive type inference.
For example, when you want to accept a function or another kind of generic value whose generic type should be inferred from some plain data. For example:
def applyTwice[A](a: A)(f: A => A): A = f(f(a))
applyTwice(10)(_ + 1) // Here the compiler is able to infer that f is Int => Int
In the above example, if I wouldn't have curried the function then I would need to have done something like: applyTwice(10, (x: Int) => x + 1) to call the function.
Which is redundant and looks worse (IMHO).
Note: In Scala 3 type inference is improved thus this reason is not longer valid there.
(and probably the main reason now in Scala 3) for the UX of callers.
For example, if you expect an argument to be a function or a block it is usually better as a single argument in its own (and last) parameter list so it looks nice in usage. For example:
def iterN(n: Int)(body: => Unit): Unit =
if (n > 0) {
body
iterN(n - 1)(body)
}
iterN(3) {
println("Hello")
// more code
println("World")
}
Again, if I wouldn't have curried the previous method the usage would have been like this:
iterN(3, {
println("Hello")
// more code
println("World")
})
Which doesn't look that nice :)
(in my experience weird but valid) when you know that majority of users will call it partially to return a function.
Because val baz = foo(bar) _ looks better than val baz = foo(bar, _) and with the first one, you sometimes don't the the underscore like: data.map(foo(bar))
Note: Disclaimer, I personally think that if this is the case, is better to just return a function right away instead of currying.
Edit
Thanks to #jwvh for pointing out this fourth use case.
(useful when using path-dependant types) when you need to refer to previous parameters. For example:
trait Foo {
type I
def bar(i: I): Baz
}
def run(foo: Foo)(i: foo.I): Baz =
foo.bar(i)

Is it possible in scala to have a generic method taking a method as an argument?

I would like to have:
def myMethod[T < ???](f: T): Unit = {
f()
}
The rest of the method is not really important but is it possible to replace ??? by somethind which would make sure T is a method
and if possible to go even further and make sure the return type of T is something defined ?
Like [T < (_*) => Int]
Thank you.
Would defining a type, like in the following trivial example, address your need?
type Fcn = String => Int
def myMethod(s: String, f: Fcn): Unit = {
println(f(s))
}
myMethod("hello", (s: String) => s.length)
// 5
You can use function literals:
def myMethod[A, T](f: A => T) {
f(someAValue)
}
or if you want functions that take no arguments:
def myMethod[T](f: () => T) {
f()
}
But judging by your comments, it seems like you specifically want to reference methods, and query the method for information about itself, which is not a feature of basic Scala. You may be able to do some of that with reflection, but reflection is an area best avoided.
Technically, you can't directly pass a method, since a method is not a value that you can instantiate and pass-around. What is usually passed around is a function instance. And when it appears that you're passing a method, the compiler is actually creating a function instance for you (method lifting or eta-expansion).
But that is not going to work if you're looking to inspect meta data about that method (name, deprecation). For that, you're probably looking for reflection. You can have your method take an instance of java.reflect.Method but that will require that you obtain that at call-site.

Scala map cannot resolve mapper function

Scala noob here.
I'm trying to apply a map in a class method:
class Miner(args: Args) extends Job(args) {
def fetchUrl(url:String) = {
...
}
TextLine(args("input")).map(url: String => fetchUrl(url))
.write(args("output"))
}
this codes breaks complaining about not being able to resolve the symbol fetchUrl.
I've thought that, fetchUrl being a one argument function, I could just omit the argument and do something like:
TextLine(args("input")).map(fetchUrl)
.write(args("output"))
This now breaks saying that I'm missing arguments for the method fetchUrl.
What gives?
Isn't mapTo a curried function?
I imagine you use this function from this object: (google redirects me to that)
mapTo[U](out: Fields)(mf: (String) ⇒ U)(implicit flowDef: FlowDef, mode: Mode, setter: TupleSetter[U]): Pipe
Perhaps you would use it like this: Textline.mapTo(args("input"))(fetchUrl)
You have some examples of mapTo usage at this page, but based on the Pipe object:
https://github.com/twitter/scalding/wiki/Fields-based-API-Reference#map-functions
Excerpt:
val savings =
items.mapTo(('price, 'discountedPrice) -> 'savings) {
x : (Float, Float) =>
val (price, discountedPrice) = x
price - discountedPrice
}
So not based on TextLine in this example, but also curried...this might be a good hint for you.

Using method to create function? The details explanation?

def first[A] :Tuple2[A,_] => A = ( pair :Tuple2[A,_] ) => pair._1
val name = first( ("Anna", 23) )
"If you take a closer look at line 2, what you see here is a method call which returns a newly created function of type Tuple2[String,Any] => String (since the compiler kicks in and infers the needed type for applying to person). Although the whole expression looks like an ordinary method call, it’s in fact a method call (to a factory method without any parameter) and a function call which follows afterwards. " -- this is the explanation of the above code.
I am not able to reason about the first step of the above process (the process creating a function object). Can someone write out a "human compiler" procedure explicitly?
EDIT: I think the fully expanded logic for line 2 should be the following two lines
val firstAsFunc= first[String];
val name = firstAsFunc(("Anna", 23))
I'm not sure to break it down further. Here's what I can think of -- I hope you get it, or that someone else is feeling more clever than I.
scala> val func = first[String] // method call
func: Tuple2[String, _] => String = <function1>
scala> val name = func( ("Anna", 23) )
name: String = Anna
The problem with the above is that func is really a getter -- a method call itself -- so I'm hardly changing anything.
EDIT
I'm not sure what you mean by formal parameter. The method first doesn't have value parameters, just type parameters. Trying to pass a value parameter to it would be a syntactical error.
When you say
(pair: Tuple2[A,_]) => pair._1
the compiler decides that you are actually saying
new Function1[Tuple2[A,_], A] {
def apply(pair: Tuple2[A,_]) = pair._1
}
That is, the first method creates a new object (of type Function1) with a method called apply which then is transparently called when you say first(...). (You would get the same thing if you wrote first.apply(...).)
(Note: Tuple2[A,_] can itself be abbreviated (A,_).)
I'm not 100% sure that I understand which bit of the process you're asking about - are you asking about what a function object is? I'll answer that question on the assumption that it is :-)
A function object is an object that derives from one of the FunctionN (Function0, Function1 etc.) traits and implements an apply method. So your example could be rewritten:
scala> def first[A]: Tuple2[A, _] => A = new Function1[Tuple2[A, _], A] { def apply(pair: Tuple2[A, _]) = pair._1 }
first: [A]=> Tuple2[A, _] => A
scala> val name = first( ("Anna", 23) )
name: java.lang.String = Anna
You can see that a function is actually an instance of FunctionN like so:
scala> def foo(x: Int, y: Double): String = "x = "+ x.toString +", "+ y.toString
foo: (x: Int, y: Double)String
scala> (foo _).isInstanceOf[Function2[_, _, _]]
res1: Boolean = true
If you take a closer look at line 2, what you see here is a method call which returns a newly created function of type Tuple2[String,Any] => String
This explanation is wrong. Line 2 does not "return a newly created function". The function is created on line 1, as explained by Rex Kerr.
Although the whole expression [on line 2] looks like an ordinary method call, it’s in fact a method call (to a factory method without any parameter) and a function call which follows afterwards.
I don't believe this is true; there is no hidden factory method going on, because the Function1 object has already been created on line 1.
One of the questions I was asking what is the formal parameter for method first.
See Wikipedia > Parameter # Computer Science

What does this piece of code mean in scala?

def func(arg: String => Int): Unit = {
// body of function
}
I mean this fragment:
String => Int
Short answer
Its a function that receives a String and returns a Int
Long answer
In Scala, functions are first class citizens. That means you can store them in variables or (like in this case) pass them around as arguments.
This is how a function literal looks like
() => Unit
This is a function that receives no arguments and returns Unit (java's equivalent to void).
This would be a function that receives a String as a parameter and returns an Int:
(String) => Int
Also, scala let's you drop the parenthesis as a form of syntactic sugar, like in your example. The preceding arg: is just the name of the argument.
Inside func you would call the function received (arg) like this:
val result = arg("Some String") // this returns a Int
As mentioned in Advantages of Scala’s Type System, it is a Functional type.
The article Scala for Java Refugees Part 6: Getting Over Java describes this syntax in its section "Higher-Order Functions".
def itrate(array:Array[String], fun:(String)=>Unit) = {
for (i <- 0 to (array.length - 1)) { // anti-idiom array iteration
fun(array(i))
}
}
val a = Array("Daniel", "Chris", "Joseph", "Renee")
iterate(a, (s:String) => println(s))
See? The syntax is so natural you almost miss it.
Starting at the top, we look at the type of the fun parameter and we see the (type1, …)=>returnType syntax which indicates a functional type.
In this case, fun will be a functional which takes a single parameter of type String and returns Unit (effectively void, so anything at all).
Two lines down in the function, we see the syntax for actually invoking the functional. fun is treated just as if it were a method available within the scope, the call syntax is identical.
Veterans of the C/C++ dark-ages will recognize this syntax as being reminiscent of how function pointers were handled back-in-the-day.
The difference is, no memory leaks to worry about, and no over-verbosity introduced by too many star symbols.
In your case: def func(arg: String => Int): Unit, arg would be a function taking a String and returning an Int.
You might also see it written (perhaps by a decompiler) as
def func(arg: Function1[String, Int]): Unit = {
// body of function
}
They are precisely equivalent.