• Scala 学习笔记之函数(2)


     1 class OldStudent extends Student {
     2 
     3   def filterName(s: String, f: String => String) = {
     4     if (s != null) f(s) else s
     5   }
     6 
     7   def mytrim(s: String) = s.trim()
     8 
     9   def talkToAll(p1Name: String, p2Name: String, p3Name: String, fn: (String, String, String) => String): String = {
    10     fn(p1Name, p2Name, p3Name)
    11   }
    12 
    13   def talkToAllCommon[A, B](p1Name: A, p2Name: A, p3Name: A, fn: (A, A, A) => B): B = {
    14     fn(p1Name, p2Name, p3Name)
    15   }
    16 
    17   def talkToAllCommon2[A, B, C](p1Name: A, p2Name: B, p3Name: C, fn: (A, B, C) => C): C = {
    18     fn(p1Name, p2Name, p3Name)
    19   }
    20 
    21 }
    22 
    23 object FunctionDemo2 {
    24   def main(args: Array[String]): Unit = {
    25     val s = new OldStudent()
    26     //高阶函数
    27     println(s.filterName(null, s.mytrim))
    28     println(s.filterName("bill", s.mytrim))
    29     //匿名函数
    30     val greeter = (name: String) => s"Hello, $name"
    31     println(greeter("world"))
    32     //无参函数
    33     def writeStart() = "write start"
    34     val writeStartVal = () => "write start val"
    35     println(writeStart)
    36     println(writeStartVal())
    37     //高阶函数匿名调用
    38     println(s.filterName(null, (s: String) => s.trim()))
    39     println(s.filterName("bill", (s: String) => s.trim()))
    40     println(s.filterName(null, s => s.trim()))
    41     println(s.filterName("bill", s => s.trim()))
    42     //占位符
    43     println(s.filterName(null, _.trim()))
    44     println(s.filterName("bill", _.trim()))
    45     //多占位符
    46     println(s.talkToAll("bill", "allen", "sky", _ + ", " + _ + ", " + _))
    47     //类型参数
    48     println(s.talkToAllCommon[String, String]("bill", "allen", "sky", _ + _ + _))
    49     println(s.talkToAllCommon[Int, Int](1, 2, 3, _ + _ + _))
    50     println(s.talkToAllCommon2[Int, Float, Double](1, 2, 3, _ + _ + _))
    51   }
    52 }
    null
    bill
    Hello, world
    write start
    write start val
    null
    bill
    null
    bill
    null
    bill
    bill, allen, sky
    billallensky
    6
    6.0
  • 相关阅读:
    2.6.2 AMQP协议和RabbitMQ基础
    2.6.1 消息队列介绍
    解决VS2015启动时Package manager console崩溃的问题
    项目管理实践
    Android动画之淡入淡出
    Android学习笔记
    Android: 解决ADB server didn't ACK
    Android: 实例解析Activity生命周期
    解决Window Azure: Failed to start Development Storage: the SQL Server instance ‘localhostSQLExpress’ could not be found.
    Spring注解之 Transactional
  • 原文地址:https://www.cnblogs.com/AK47Sonic/p/7071065.html
Copyright © 2020-2023  润新知