我正在使用Scala 2.9.2。我想为变量分配一个未命名的函数,但我似乎无法直接获得语法。如果我定义一个命名函数,然后将命名函数分配给变量,它似乎工作正常,如此处的会话所示。
$ scala
Welcome to Scala version 2.9.2 (OpenJDK Server VM, Java 1.7.0_65).
Type in expressions to have them evaluated.
Type :help for more information.
scala> type Foo = String => Int
defined type alias Foo
scala> def myFoo (s : String) : Int = s match {case "a" => 123 case _ => s.length ()}
myFoo: (s: String)Int
scala> val foo : Foo = myFoo
foo: String => Int = <function1>
scala> foo ("b")
res0: Int = 1
scala> foo ("a")
res1: Int = 123
到目前为止,这么好。此时我认为我可以定义一个未命名的函数并将其分配给变量,但似乎我无法弄清楚语法。我尝试了几种变化,但没有一种变化。
scala> val bar : Foo = (s : String) : Int = s match {case "a" => 123 case _ => s.length ()}
<console>:1: error: ';' expected but '=' found.
val bar : Foo = (s : String) : Int = s match {case "a" => 123 case _ => s.length ()}
^
scala> val bar : Foo = (s : String) => Int = s match {case "a" => 123 case _ => s.length ()}
<console>:8: error: reassignment to val
val bar : Foo = (s : String) => Int = s match {case "a" => 123 case _ => s.length ()}
^
scala> val bar : Foo = ((s : String) => Int) = s match {case "a" => 123 case _ => s.length ()}
<console>:1: error: ';' expected but '=' found.
val bar : Foo = ((s : String) => Int) = s match {case "a" => 123 case _ => s.length ()}
^
scala> val bar : Foo = (s : String) : Int => s match {case "a" => 123 case _ => s.length ()}
<console>:1: error: ';' expected but 'match' found.
val bar : Foo = (s : String) : Int => s match {case "a" => 123 case _ => s.length ()}
^
scala>
对于基本问题感到抱歉,但有人可以指出正确的语法吗?
答案 0 :(得分:3)
val bar: String => Int = s => s match { case "a" => 123 case _ => s.length() }
或只是
val bar = (s: String) => s match { case "a" => 123 case _ => s.length() }
或更好:
val bar: String => Int = { case "a" => 123 case s => s.length() }
而且,从另一个方向来看......
val bar = { case "a" => 123 case s => s.length() }: String => Int
答案 1 :(得分:2)
我相信以下是你想要的:
val bar: String => Int = s => s match {case "a" => 123 case _ => s.length ()}
或更简洁:
val bar: String => Int = { case "a" => 123 case s => s.length ()}