gpt4 book ai didi

scala - Scala 中的隐式类

转载 作者:行者123 更新时间:2023-12-04 13:26:07 24 4
gpt4 key购买 nike

下面是 Scala 隐式类的示例程序:

object Run {
implicit class IntTimes(x: Int) {
def times [A](f: =>A): Unit = {
def loop(current: Int): Unit =

if(current > 0){
f
loop(current - 1)
}
loop(x)
}
}
}

还有一个类调用“ 4 times println("hello")”如下,但我不明白“ 4 times println("hello")”是什么意思?
object Demo {
def main(args: Array[String]) {
4 times println("hello")
}
}

最佳答案

4 times println("hello")大致翻译成:

val c = new IntTimes(4)
c.times(println("hello"))

也就是说,因为有一个隐式类接受 Int作为其唯一参数,使用方法 times , 做 4.times使用 4 作为参数隐式实例化类,然后调用 times在上面。

关于scala - Scala 中的隐式类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40878893/

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