risc-v中文社区

 找回密码
 立即注册
查看: 1051|回复: 2

[原创] risc-v开发基础 Scala 偏函数与Function1的实验---(26)

  [复制链接]

347

主题

564

帖子

2237

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2237
发表于 2021-8-27 08:57:03 | 显示全部楼层 |阅读模式
val too:Function1[Int,Int] = {
  case x =>x + x + x
}
println(too)  //其实是Function1这个trait的toString 源码:override def toString() = "<function1>"
println(too(3)) //9
def fun(i:Int):Int = {
  i+i+i
}
println(fun(3)) //9
def too2:Function1[Int,Int] = {
  case x => x + x + x
}
println(too2) //<function1>
println(too2(3)) //9
//    val pf: PartialFunction[Int,Int] = too2.asInstanceOf[PartialFunction[Int,Int]] //java.lang.ClassCastException: com.joe.stu.PartialFunctionTest$$anonfun$too2$1$1 cannot be cast to scala.PartialFunction
//    println(pf(3))
//    val pf: PartialFunction[Int,Int] = fun  或too 或too2 都会提示类型转换有错误
val pxf: PartialFunction[Int,Int] = {
  case x => x + x +x
}
val pxf1:Function1[Int,Int] = pxf
println(pxf1(3)) //9



回复

使用道具 举报

347

主题

564

帖子

2237

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2237
 楼主| 发表于 2021-8-27 09:05:10 | 显示全部楼层
def fun2(a:Int,b:Int):Function2[Int,Int,Int] = (a,b)=>{
  a+b+10
}
println(fun2(1,2)) //<function2>
println(fun2(1,2)(2,3)) //15

回复

使用道具 举报

347

主题

564

帖子

2237

积分

管理员

Rank: 9Rank: 9Rank: 9

积分
2237
 楼主| 发表于 2021-8-27 09:07:38 | 显示全部楼层
def fun3:Function2[Int,Int,Int] = (a,b)=> a+b +11
println(fun3(2,3)) //16
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则



Archiver|手机版|小黑屋|risc-v中文社区

GMT+8, 2024-4-30 08:47 , Processed in 0.019708 second(s), 17 queries .

risc-v中文社区论坛 官方网站

Copyright © 2018-2021, risc-v open source

快速回复 返回顶部 返回列表