How to define Scala closure with explicit return type
Why doesn't this work in scala:
val cloz: (Int,String => String) = (num: Int开发者_Go百科, str: String) => {
str+"-"+num
}
I see a few examples of closures being defined with only 1 arg, like this:
val thingy: (Int => Int) = (num: Int) => {
num * 2
}
But absolutely nowhere (including Scala ebooks) could I find any information explaining the syntax of "val" closures.
Thanks! Jamie
The correct syntax is:
val cloz: (Int, String) => String = (num: Int, str: String) => {
str + "-" + num
}
By the way, in this simple case you can also simplify expression like this (especially if you already explicitly specifying the type of the function):
val cloz: (Int, String) => String = (num, str) => str + "-" + num
Update
You can also use REPL to explore Scala - it's very nice tool. You can start it just by starting scala
without any arguments. Here is example session:
scala> val cloz = (num: Int, str: String) => str + "-" + num
cloz: (Int, String) => java.lang.String = <function2>
scala> val cloz: (Int, String) => String = (num: Int, str: String) => {
| str + "-" + num
| }
cloz: (Int, String) => String = <function2>
scala> val cloz: (Int, String) => String = (num, str) => str + "-" + num
cloz: (Int, String) => String = <function2>
scala> def printCloz(cloz: (Int, String) => String, num: Int, str: String) = print(cloz(num, str))
printCloz: (cloz: (Int, String) => String, num: Int, str: String)Unit
As you can see it not only allows you to interactively execute code, but also prints type information if you define something.
Based on the excellent answer from @Eazy Angel, I offer this for anyone who's confused as I was:
val cloz: (Int,String) => String = (num, str) => {
str+"-"+num
}
def f1( clozArg: ((Int,String) => String), intArg: Int, stringArg: String ): String = {
clozArg(intArg,stringArg)
}
println("f1 result="+f1(cloz, 5, "okee"))
Please note however (please correct me if I'm wrong) that b/c of Scala's type inference you are not required to specify all these types explicitly. The only time I have seen so far that you must do is when using recursion.
--
UPDATE:
This bizarre syntax works also: (see return type on 3rd line)
val cloz = (num: Int, str: String) => {
str+"-"+num
} : String
def f1( clozArg: ((Int,String) => String), intArg: Int, stringArg: String ): String = {
clozArg(intArg,stringArg)
}
println("f1 result="+f1(cloz, 5, "okee"))
精彩评论