What does this piece of code mean in scala?

def func(arg: String => Int): Unit = {
    // body of function
}

I mean this snippet: String => Int

+3
source share
3 answers

As mentioned in Advantages of the Scala s type system , this is a Functional Type .

In a Scala article for Java Refugees, Part 6: "Java Overloading" describes this syntax in the "Higher Order Functions" section.

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))

? , .
, fun, (type1, …)=>returnType, .
fun , String Unit ( , ).
, . fun , , , .
C/++ , . , , , , .


: def func(arg: String => Int): Unit, arg , String Int.

+4

, Int

Scala . , ( ) .

() => Unit

, Unit (java void).

, Int:

(String) => Int

, scala , . arg: - .

func (arg) :

val result = arg("Some String") // this returns a Int
+9

You can also see it written (possibly by a decompiler) as

def func(arg: Function1[String, Int]): Unit = {
    // body of function
}

They are exactly equivalent.

+4
source

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


All Articles