gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 10:37:14 25 4
gpt4 key购买 nike

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

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com