converting method to function? - scala

1) How is this construction called? Cannot google it.
2) Why it doesn't work? I expect message be printed.
class A {
def m() {
println("m()")
}
}
object Main {
def main(args: Array[String]) {
val fun = (_: A).m _
fun(new A())
}
}

As om-nom-nom says, the conversion of methods to functions is called "partial application." It can be expressed explicitly by using underscore(s) as "arguments" to a method or automatically by the compiler when the available type information is sufficient for it to infer that a method name used in a place where a function is required can be partially applied to produce the required function.
Now, for your code. As written, the result of the call fun(new A()) is a Function1[Unit, Unit]. You'd have to apply that function to get the println invoked
// Exiting paste mode, now interpreting.
defined class A
defined module Main
scala> Main.main(Array())
scala> def doIt { val fun = (_: A).m _; fun(new A())() }
doIt: Unit
scala> doIt
m()

Related

Method overloading in scala gives compilation error ambiguous reference

When I compile this code, I get ambiguous reference error for method m1. Can someone tell me why?
object MyClass {
trait T {
def m1(str: String): Unit = println(str)
def m1: Unit = {
println("m1")
m1("from:m1")
}
}
class C extends T {
override def m1(str: String): Unit = println(str+"1")
}
def main(args: Array[String]): Unit = {
val c = new C()
c.m1
}
}
When you call C.m1 in main you don't include parentheses. The compiler doesn't know if you are intentionally calling the arity-0 method, or were intending to call the arity-1 method using infix notation, eg c.m1 "hello".
Replacing c.m1 with c.m1() will compile.

play/scala , implicit request => what is meaning? [duplicate]

This question already has an answer here:
Implicit parameter for literal function
(1 answer)
Closed 6 years ago.
Most of the play framework I see the block of code
// Returns a tasks or an 'ItemNotFound' error
def info(id: Long) = SecuredApiAction { implicit request =>
maybeItem(Task.findById(id))
}
yes my understanding is define a method info(id: Long) and in scala doc to create function in scala the syntax look like this:
def functionName ([list of parameters]) : [return type] = {
function body
return [expr]
}
Can you tell me what is the meaning of implicit request => and SecuredApiAction put before {
play.api.mvc.Action has helper methods for processing requests and returning results. One if it's apply overloads accepts a play.api.mvc.Request parameter:
def apply(request: Request[A]): Future[Result]
By marking the request parameter as implicit, you're allowing other methods which implicitly require the parameter to use it. It also stated in the Play Framework documentation:
It is often useful to mark the request parameter as implicit so it can
be implicitly used by other APIs that need it.
It would be same if you created a method yourself and marked one if it's parameters implicit:
object X {
def m(): Unit = {
implicit val myInt = 42
y()
}
def y()(implicit i: Int): Unit = {
println(i)
}
}
Because there is an implicit in scope, when invoking y() the myInt variable will be implicitly passed to the method.
scala> :pa
// Entering paste mode (ctrl-D to finish)
object X {
def m(): Unit = {
implicit val myInt = 42
y()
}
def y()(implicit i: Int): Unit = {
println(i)
}
}
// Exiting paste mode, now interpreting.
defined object X
scala> X.m()
42

Tunnel implicit parameter to call-by-name function body

Consider following code snippet:
object Example {
def run(f: => Unit): Unit = {
implicit val i = 1
f
}
def caller(): Unit =
run {
todo
}
def todo(implicit i: Int): Unit =
println(i)
}
which currently is not compiling with following message:
Error:(14, 13) could not find implicit value for parameter i: Int
todo
^
My question is it possible to make implicit parameter available to call-by-name function body?
EDIT
I tried make it working with macro implementation as suggested by Alexey Romanov
import scala.language.experimental.macros
import scala.reflect.macros.whitebox.Context
object Macros {
def run(f: => Unit): Unit = macro runImpl
def runImpl(c : Context)(f: c.Tree) = {
import c.universe._
q"""{
implicit val i: Int = 3
$f
}"""
}
}
object Example extends App {
Macros.run {
todo
}
def todo(implicit i: Int): Unit =
println(i)
}
Debugging macro i can see that it is correctly expanded into
{
implicit val i: Int = 3
Example.this.todo
}
Unfortunately it does not compiles as well with same error that implicit is not found.
Digging into issue i found discussions here and jira issues https://issues.scala-lang.org/browse/SI-5774
So question is the same: Is it possible to tunnel implicit into todo function in this case?
Simply said - no. implicit requires that it is obvious from the code what is going on. If you want anything to be passed to a function implicitly, it must have implicit parameter which is not the case of your f function.
This is a great source of wisdom related to implicit:
http://docs.scala-lang.org/tutorials/FAQ/finding-implicits.html
My question was more about why implicit defined in run is not tunneled into caller's run body
Because that's simply not how lexical scoping works. It isn't in scope where the body is defined. You have two good alternatives:
def run(f: Int => Unit) = f(1)
run { implicit i =>
todo // can use i here
}
Make run a macro. This should be at least an approximation (adapted from SI-5778), unfortunately I can't test it at the moment:
object Macros {
def run(f: => Unit) = macro runImpl
def runImpl(c : Context)(f: c.Tree) = q"""{
implicit val i: Int = 1
// some other implicits
$f
}"""
}

Scala bug? DelayedInit and Implicits

I've found extremely weird behaviour (scala 2.9.1 ) using and defining implicit values, and wondering if anyone can explain it, or if it's a scala bug?
I've created a self contained example:
object AnnoyingObjectForNoPurpose {
trait Printer[T] {
def doPrint(v: T): Unit
}
def print[T : Printer](v: T) = implicitly[Printer[T]].doPrint(v)
trait DelayedRunner extends DelayedInit {
def delayedInit(x: => Unit){ x }
}
// this works, as it should
object Normal extends DelayedRunner {
implicit val imp = new Printer[Int] {
def doPrint(v: Int) = println(v + " should work")
}
print(343)
}
// this compiles, but it shouldn't
// and won't run, cause the implicit is still null
object FalsePositive extends DelayedRunner {
print(123)
implicit val imp = new Printer[Int] {
def doPrint(v: Int) = println(v + " should not compile")
}
}
def main(args: Array[String]) {
implicit val imp = new Printer[Int] {
def doPrint(v: Int) = println(v + " should work")
}
print(44)
// print(33.0) // correctly doesn't work
Normal // force it to run
FalsePositive // force this to run too
}
}
Suppose you changed your definition of delayInit to be a no-op, i.e.
def delayedInit(x: => Unit) { }
Then in your main method do something like
println("FP.imp: " + FalsePositive.imp)
As expected that will print FP.imp: null, but the real point of the exercise is to illustrate that the block that defines the body of FalsePositive is acting like a regular class body, not a function body. It's defining public members when it sees val, not local variables.
If you added a method to AnnoyingObjectForNoPurpose like the following, it wouldn't compile because print's implicit requirement isn't satisfied.
def fails {
print(321)
implicit val cantSeeIt = new Printer[Int] {
def doPrint(v: Int) = println(v + " doesn't compile")
}
}
However if you defined a class along the same principle, it would compile, but fail at runtime when initialized, just like your FalsePositive example.
class Fine {
print(321)
implicit val willBeNull = new Printer[Int] {
def doPrint(v: Int) = println(v + " compiles, but fails")
}
}
To be clear, the compile behavior of Fine has nothing to do with the presence of the implicit. Class/object initializers are very happy to compile with val initializers which reference undefined vals.
object Boring {
val b = a
val a = 1
println("a=%s b=%s".format(a, b))
}
Boring compiles just fine and when it is referenced, it prints a=1 b=0
It seems like your question boils down to "Should the body of a class/object deriving from DelayedInit be compiled as if it's a class body or a function block?"
It looks like Odersky picked the former, but you're hoping for the latter.
That's the same bug as if I write this:
object Foo {
println(x)
val x = 5
}
It ain't a bug. Your constructor flows down the object body and happens in order. DelayedInit isn't the cause. This is why you need to be careful when using val/vars and ensure they init first. This is also why people use lazy val's to resolve initialization order issues.

scala: override implicit parameter to constructor

I have a class that takes an implicit parameter which is used by functions called inside class methods. I want to be able to either override that implicit parameter, or alternatively, have the implicit argument be copied from its source. As an example:
def someMethod()(implicit p: List[Int]) {
// uses p
}
class A()(implicit x: List[Int]) {
implicit val other = List(3) // doesn't compile
def go() { // don't want to put implicit inside here since subclasses that override go() have to duplicate that
someMethod()
}
}
The behavior I want is that someMethod() gets an implicit parameter that is some changed version of x, which was the class's implicit parameter. I want to be able to either mutate x without changing it for whatever passed it into A's constructor, or otherwise override it to a new value of my choosing. Both approaches don't seem to work. That is, it doesn't copy the list in the former case, and the compiler finds an ambiguous implicit value for the latter case. Is there a way to do this?
I realize that I can redefine the implicit value within go(), but this is not a good choice in my case because this class is subclassed numerous times, and I'd like to handle this implicit change in the base class only. So it doesn't necessarily need to go in the constructor, but it must be in a method other than go().
Introduce another wrapper type, simply to disambiguate:
// badly named, choose something domain-specific
case class ListHolder(theList: List[Int])
def someMethod()(implicit holder: ListHolder) {
val xs = holder.theList
// uses xs ...
}
class A()(implicit xs: List[Int]) {
implicit val other = ListHolder(42 :: xs) // compiles
def go() {
// xs is never considered for the implicit param to someMethod()
// because it's now the wrong type
}
}
This also makes the code more self-documenting, as it becomes blindingly obvious that the two implicits are not one and the same.
If you want to have zillions of implicits floating around that don't collide with each other, you can create a wrapper class that you can tag with marker traits for implicit usage. There are a variety of syntaxes you could use; here's one example:
object Example {
class Implication[A,B](val value: A) {
def apply[C](c: C) = new Implication[C,B](c)
}
object Implication {
def mark[B] = new Implication[Unit,B](())
implicit def implication_to_value[A,B](i: Implication[A,B]) = i.value
}
trait One {}
trait Two {}
implicit val x = Implication.mark[One]("Hello")
implicit val y = Implication.mark[Two]("Hi")
def testOne(implicit s: Implication[String,One]) = println(s: String)
def testTwo(implicit s: Implication[String,Two]) = println(s: String)
def testThree(s: String) = println("String is " + s)
def main(args: Array[String]) {
testOne
testTwo
testThree(x)
testThree(y)
}
}
Which works as you would hope:
scala> Example.main(Array())
Hello
Hi
String is Hello
String is Hi
Since you have to use a wrapper object, it's not super-efficient, but it can be very effective. (Or very confusing, given how much happens implicitly.)
This modification compiles. I changed x into a var:
class A()(implicit var x: List[Int]) {
def someMethod()(implicit p: List[Int]) {
// uses p
}
x = List(3)
def go() { // don't want to put implicit inside here since subclasses that override go() have to duplicate that
someMethod()
}
}