【问题标题】:Implicit Classes in ScalaScala 中的隐式类
【发布时间】:2016-11-30 01:45:29
【问题描述】:

以下是 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")
   }
}

【问题讨论】:

标签: scala


【解决方案1】:

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

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

也就是说,由于有一个隐式类将Int 作为其唯一参数,使用方法times,执行4.times 隐式实例化以4 作为参数的类,然后调用times on它。

【讨论】:

    【解决方案2】:

    我还发现这个示例过于复杂,无法演示隐式类。

    简而言之,隐式类用新的方法和属性覆盖其他类。

    在这个例子中,它重写了 Int 来给它一个方法 times。 times 方法采用具有通用返回类型的按名称调用参数:

    def times [A](f: =>A): Unit
    

    意味着 f 是一个返回泛型类型 A 的函数。

    当使用名称调用变量时,它调用函数并成为返回值。 在 times 方法中,它使用递归来循环调用 f 的整数次数。

    在 scala 中,您可以使用点或空格来调用方法,而参数不需要括号, 所以object.method(param1, param2) 可能是object method param1 param2

    因此最后一次通话4 times println("hello") 其实是4.times(println("hello"))

    【讨论】:

    • 我在这里有点困惑。我看到方法“times”采用不接受任何输入并返回 A 作为输出的功能参数。但是在“times”的调用中,函数 println 被传递,它接受一个字符串作为 i/p 并返回 Unit。这与签名正好相反。但这是有效的。有人可以帮我理解。提前致谢!
    • 看到 f 具有按名称调用的语义很有用,因此对 f 的评估会延迟到实际执行调用 f 的主体中的行。 loop 的函数体的大括号已被跳过,以显示函数体仅包含 if 语句。所以,times 方法只定义了loop 并调用了一次。
    猜你喜欢
    • 2015-01-16
    • 1970-01-01
    • 1970-01-01
    • 2020-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多