Scala:为什么我的函数不能打印字符串参数?

标签 scala

假设我有一个接受一个参数的函数。

def weird(nothing: Unit): Unit = {
  println(nothing)
}

weird("Print me!")

当我将一个字符串传递给该函数时,它会打印 ()。为什么会这样?

为什么 UnitString 相同?

最佳答案

提供单位值,“丢弃”您的字符串值。

scala> ("hi": Unit)
<console>:11: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses
       ("hi": Unit)
        ^

scala> :replay -Ywarn-value-discard
Replaying: ("hi": Unit)
<console>:11: warning: discarded non-Unit value
       ("hi": Unit)
        ^
<console>:11: warning: a pure expression does nothing in statement position; you may be omitting necessary parentheses
       ("hi": Unit)
        ^

查看转换 in the spec .

这只是使您的表达式适应预期类型的​​一种方式。

通常,它看起来像:

def f: Unit = 42  // add () here

你的电话其实是

weird { "string" ; () }

关于Scala:为什么我的函数不能打印字符串参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33137188/

相关文章:

scala - if (Option.nonEmpty) 与 Option.foreach

scala - 在使用该 UDF 的列上添加过滤器时,Spark Sql UDF 抛出 NullPointer

arrays - 在 Scala 中获取数组元素仅适用于显式应用方法

java - scala - 将 Mahout vector 转换为数组

Scala - Seq 的大小和长度有什么区别?

scala - 如何在 Play 2.6.x 中将 java.io.File 转换为 Scala 临时文件

postgresql - 如何在 slick 3 的 DBIOAction 组合中使用 Future?

scala - scala 中并行或顺序收集的类型

scala - 为什么 Spark 应用程序以 “ClassNotFoundException: Failed to find data source: kafka” 作为带有 sbt 程序集的 uber-jar 失败?

java - 从 jar 中提取 scala 源代码