scala(或intellij问题)(1到10 x 3)toList和(1到10 x 3).toList有什么区别?

时间:2018-11-22 08:40:50

标签: scala intellij-idea

如果这个问题很愚蠢,请谅解。

我开始用基本语法学习scala。

但是我不明白为什么一个是错误而另一个不是。我使用scala工作表对此进行了测试

val range = 1 to 10 by 3 toList
println(s"$range") //error

但是下面是列表(实际上是Seq)

val range = (1 to 10 by 3).toList
println(s"$range") //no problem

我正在使用intellij 2018.2 Ultimate Edit。

编辑:图像已更改。我附加了包含的捕获错误消息,而不是警告。 enter image description here

编辑:我认为这是intellij版本的问题,但仍然无法正常工作

2 个答案:

答案 0 :(得分:1)

应该都可以。在scala中,您可以省略.并保留用于方法调用的空间,这可能是haskell方法的损坏版本。我认为根据官方文档,不建议在Scala中使用空格-STYLE GUIDE - METHOD INVOCATION

示例:

scala> val data = "guitar"
data: String = guitar

scala> data.toUpperCase
res8: String = GUITAR

您可以使用空格代替.

scala> data toUpperCase
<console>:13: warning: postfix operator toUpperCase should be enabled
by making the implicit value scala.language.postfixOps visible.
This can be achieved by adding the import clause 'import scala.language.postfixOps'
or by setting the compiler option -language:postfixOps.
See the Scaladoc for value scala.language.postfixOps for a discussion
why the feature should be explicitly enabled.
       data toUpperCase
            ^
res9: String = GUITAR

由于.toUpperCase在不包含.的数据结构之后使用(称为postfix Operator),因此编译器只是在警告这一点。可以按照警告中的说明进行修复,

scala> import scala.language.postfixOps
import scala.language.postfixOps

scala> data toUpperCase
res10: String = GUITAR

同样的情况适用于您的示例。从可读性的角度来看,点使示例更具可读性。

scala> (1 to 10 by 3).toList
res9: List[Int] = List(1, 4, 7, 10)

此外,后缀运算符可能会导致错误。例如,1 + "11" toInt在计算结束时应用toInt,但也许我想要的是1 + "11".toInt

还,关于您的错误,您还需要对编译器大喊大叫,以停止在toList上用;进行链接,或者在后缀运算符后换行。或者,您可以在后缀运算符后使用valdef,这样编译器现在知道它是不同的上下文。

scala> :paste

    import scala.language.postfixOps
    val range = 1 to 10 by 3 toList

    println(s"$range")

// Exiting paste mode, now interpreting.

List(1, 4, 7, 10)
import scala.language.postfixOps
range: List[Int] = List(1, 4, 7, 10)

另请参阅:Let’s drop postfix operators

答案 1 :(得分:1)

如果遇到此错误...

  

错误:(2,13)递归惰性值范围需要输入

...这是因为您在不应该使用的位置使用了中缀(无点)表示法。

println()之前放置一个空白行,或在toList之后放置一个分号,它将起作用。

错误的原因是instance.method(argument)可以变成...

instance method argument

...但是如果您尝试将instance.method转换为...

,编译器通常会感到困惑。
instance method

编译器将查找丢失的argument,直到遇到分号或空白行为止。

相关问题