Underline after function?

Considering

scala> def method(x: Int) = x
method: (x: Int)Int

scala> val func = (x: Int) => x
func: Int => Int = <function1>

Consider the following code:

scala> method _
res0: Int => Int = <function1>

scala> func(_)
res1: Int => Int = <function1>

scala> func _
res2: () => Int => Int = <function0>

I understand that it res0is an extension of eta, but is res1equivalent to a lambda function (x) => func(x). But I can not understand the result res2. Can anyone explain this to me?

+4
source share
4 answers

This is actually a bit complicated. First, let's see what happens outside the REPL:

Doesn't work when funcis a local variable:

object Main extends App {
  def foo() = {
    val f = (_: Int) + 1
    f _
  }

  println(foo())
}

[error] /tmp/rendereraEZGWf9f1Q/src/main/scala/test.scala:8: _ must follow method; cannot follow Int => Int
[error]     f _
[error]     ^

But if you put it out def foo, it will compile:

object Main extends App {
  val f = (_: Int) + 1
  val f1 = f _

  println(f1)
}

because it fis both a field Mainand a method with no arguments, which returns the value of this field.

, REPL ( Scala trait/class/object),

scala> val func = (x: Int) => x
func: Int => Int = <function1>    

-

object Line1 {
  val func = (x: Int) => x
}
import Line1._
// print result

, func Line1.func, .

+5

eta, res2 , 0 , .

res2: () => Int => Int = <function0>

, :

val zero = func _
val f: Int => Int = zero()
+2
val func1 = func _

0, func.

:

func1()(2) // outputs 2

:

val func2 = func1 _

func2()()(2) // outputs 2
+1

res2 - _ .

.

scala> func _

This means that you partially applied yours <function1>. This leads to a new curry form, the first function of which takes zero arguments (hence <function0>)

() =>

Which returns the original <function1>, which takes 1 argument.

Int => Int = <function1>

The full result is a chain of functions.

res2: () => Int => Int = <function0>

A rule that may be useful for you to remember is that the functions are connected on the right, so the following equivalents.

() => Int => Int    
() => (Int => Int)

This other post may be helpful to you.

+1
source

Source: https://habr.com/ru/post/1655064/


All Articles