• scala学习笔记:无参函数


    scala> def repeat(times:Int)(run:()=>Unit)=for(i<-1 to times)run()
    repeat: (times: Int)(run: () => Unit)Unit
    
    scala> repeat(2){println("haha~~~")}
    <console>:9: error: type mismatch;
     found   : Unit
     required: () => Unit
                  repeat(2){println("haha~~~")}
                                   ^
    
    scala> repeat(2){()=>println("haha~~~")}
    haha~~~
    haha~~~

    为了去掉()=>这样的写法,将run()方法声明为没有参数的函数:

    scala> def repeat(times:Int)(run: =>Unit)=for(i<-1 to times)run
    repeat: (times: Int)(run: => Unit)Unit
    
    scala> repeat(2){println("haha~~~")}
    haha~~~
    haha~~~

    以上方法把任意的表达式或者代码块转换为一个函数对象。

  • 相关阅读:
    SciPy
    时间序列
    bytes 与 str 转换
    tensorflow
    Python3+Cuda+Cudnn+GPU
    TensorFlow models
    saltstack
    docker
    分布式文件系统
    创建RHCS集群环境 创建高可用Apache服务
  • 原文地址:https://www.cnblogs.com/bluejoe/p/5115868.html
Copyright © 2020-2023  润新知