当前位置:网站首页>scala-for推导:能够在for表达式中的最初部分定义值,并在(外面)后面的表达式中使用该值
scala-for推导:能够在for表达式中的最初部分定义值,并在(外面)后面的表达式中使用该值
2022-06-22 15:24:00 【ZH519080】
在scala的for循环中,如何在不适用容器的情况下,在for循环(外面)后面调用其for中定义的属性。对象中包含None属性在for中如何剔除???
两种情况写在同一个函数里面:
/**for推导:能够在for表达式中的最初部分定义值,病在后面的表达式中使用该值
* 如upcaseBreed在println中使用*/
def roundingFor: Unit ={
val dogBreeds = List("Doberman","Dachshund","Scottish","Portuguese")
for {
breed <- dogBreeds
/**尽管upcaseBreed的值不可变,upcaseBreed不需要在前面设定,但并不需要使用val关键字进行限定*/
upcaseBreed = breed.toUpperCase
} println(upcaseBreed) //相当于在for循环后面使用for内的属性
println(
""" *
| ***
| *****
|*********
| *****
| ***
| *
""".stripMargin)
val catBreeds = List(Some("Dane"),None,Some("Yorkshire"),None,Some("Scottish"))
println("first pass:")
for {
/**每个被提取的元素均为Option对象。而后续的代码中将使用箭头符提取Option中的值,推导式会进行有效的检查并忽略None,不会有异常*/
breedOption <- catBreeds
breed <- breedOption
upcaseBreed = breed.toUpperCase
} println(upcaseBreed)
println("second pass:")
/**在第一个for循环内部定义的breed和upcaseBreed属性在下面的第二个for循环中使用*/
for {
/**此for推导式使用了模式匹配,只有当breedOption是Some类型时,表达式Some(breed) <- catBreeds才会执行并提取出breed*/
Some(breed) <- catBreeds
upcaseBreed = breed.toUpperCase
} println(upcaseBreed)
}
边栏推荐
猜你喜欢

【微信小程序获取自定义tabbar的高度】绝对可用!!!

Runtime -- explore the nature of classes, objects, and classifications
![[pop up box 2 at the bottom of wechat applet package]](/img/31/266e6a1f4200347c9324ea37b78562.png)
[pop up box 2 at the bottom of wechat applet package]

【微信小程序封装底部弹出框二】
![[pop up box at the bottom of wechat applet package] I](/img/28/7cb36ef4fcf753764cc9363a323a20.png)
[pop up box at the bottom of wechat applet package] I

Conversion between numeric types and strings

JS获取数据类型方法总结

SAP ABAP internal tables: create, read, populate, copy and delete-06

How to add a "security lock" to the mobile office of government and enterprises?
![[C language] use of library function qsort](/img/b0/6e86e31243164479b0f3d960d039ef.png)
[C language] use of library function qsort
随机推荐
What is SAP ABAP? Type, ABAP full form and meaning
ERROR 1364 (HY000): Field ssl_cipher doesnt have a default value
nio编程service
How to add a "security lock" to the mobile office of government and enterprises?
Test for API
如何为政企移动办公加上一道“安全锁”?
安全信得过!天翼云数据安全管理平台通过评测
find命令使用
【C语言】库函数qsort的使用
Test for API
CUMT study diary - quick notes of digital image processing examination
Consumption monitoring of Prometheus monitoring [consult exporter]
【小程序项目开发-- 京东商城】uni-app开发之分包配置
jsp学习之(一)---------jsp概述
[deep anatomy of C language] keywords if & else & bool type
SAP ABAP 中的模块化:宏、子程序和功能模块 -04
【游标的嵌套】mysql存储过程游标的嵌套
[MYSQL]一台windows电脑安装多个mysql-不同版本
nio使用可写事件处理一次性写不完情况
为数字添加千分位符号(金额千分位)