gpt4 book ai didi

scala - 为什么允许我将返回非 Unit 的函数传递给采用返回 Unit 的函数的方法?

转载 作者:行者123 更新时间:2023-12-05 00:24:17 28 4
gpt4 key购买 nike

这是代码:

def filterAcc(p: Tweet => Boolean, acc: TweetSet): TweetSet = {
foreach(tweet =>
if(p(elem)) acc.incl(elem)
else acc.incl(elem))
acc
}

def foreach(f: Tweet => Unit): Unit = {
f(elem)
left.foreach(f)
right.foreach(f)
}

def incl(x: Tweet): TweetSet = {
if (x.text < elem.text) new NonEmpty(elem, left.incl(x), right)
else if (elem.text < x.text) new NonEmpty(elem, left, right.incl(x))
else this
}
foreach需要 f ,返回 Unit . incl返回 TweetSet .
看来我传递给 filterAcc 的函数返回 TweetSet , 因为 if 和 else 中的最后一行都调用了 incl .即使一个值出现在返回 Unit 的函数的最后一行,是否也是这种情况? ,它根本不会返回那个值?对不起,如果这是一个基本问题,我是一个全新的程序员。

最佳答案

这是 Unit 的特例.如果你传递一个函数 f (或值)将非 Unit 类型返回给另一个需要 Unit 的函数类型,非 Unit 值被丢弃以支持 Unit .
来自 Scala spec - 6.26.2 Value Conversions :

Value Discarding

If e has some value type and the expected type is Unit, e is converted to the expected type by embedding it in the term { e; () }.


这在您调用返回值不是 Unit 的副作用函数的情况下很有用。 ,但您并不关心值(value)是什么(无论出于何种原因)。

关于scala - 为什么允许我将返回非 Unit 的函数传递给采用返回 Unit 的函数的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26600132/

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