繁体   English   中英

Scala中的def f = x:Int-> List(x-1,x,x + 1)有什么问题?

[英]What is wrong with def f=x:Int->List(x-1,x,x+1) in Scala?

嗨,我不太明白为什么Scala中的此定义不起作用。

scala> def f=x:Int->List(x-1,x,x+1)
<console>:1: error: ';' expected but '(' found.
       def f=x:Int->List(x-1,x,x+1)
                        ^

有两个直接的问题:

  1. ->应该是=>
  2. x:Int应该是(x:Int)

所以这工作:

def f = (x: Int) => List(x - 1, x, x + 1)

但是,这定义了一个返回函数的函数,这可能不是预期的。 因此,请尝试

val f = (x: Int) => List(x - 1, x, x + 1)

要么

def f(x: Int) = List(x - 1, x, x + 1)

这在语法上是不正确的:我认为您想要的是:

def f(x: Int):List[Int] = List(x-1,x,x+1)

首先,使用=>而不是->定义函数类型,例如,您可能来自haskell ,因此,例如,具有Int参数且返回List[Int]的函数将具有Int => List[Int]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM