scala 转换为字符串_如何在Scala中将列表转换为选项?

scala 转换为字符串

In programming, there might be cases when the programmer needs to keep a check on data structure so that only non-empty collection can be processed to avoid errors and exceptions in the code. One such case can be when the program contains a list that can be empty, hence we have to convert the empty list to none by converting the list to option.

在编程中,有时程序员需要检查数据结构,以便只能处理非空集合,以避免代码中的错误和异常。 当程序包含一个可以为空的列表时,就是这种情况。因此,我们必须通过将列表转换为option来将空列表转换为空列表。

This option will give the list if not empty otherwise will return none.

如果不为空,此选项将给出列表,否则将不返回任何列表。

List in Scala is a collection that stores data in the form of a liked-list.

Scala中的List是一个集合,以喜欢列表的形式存储数据。

Example:

例:

List(12, 54, 12 , 87)

Option in Scala is a container that contains one single value which can be one of the two distinct values.

Scala中的Option是一个包含一个单一值的容器,该值可以是两个不同值之一。

将列表转换为选项 (Convert List to Option)

For this conversion, we need to check if the list is empty or not.

对于此转换,我们需要检查列表是否为空。

If the list is empty, we will convert in the option value otherwise, leave it the same. This is done using the option.

如果列表为空,我们将转换选项值,否则,将其保留不变。 这是使用选项完成的。

Scala程序将列表转换为选项 (Scala program to convert list to option )

object MyClass {
    def listToOption(myList : List[Int] ) : Option[opt] = {
        Option(myList).filter(_.nonEmpty).map(opt)
    }
    case class opt(list : List[Int]) {}
    
    def main(args: Array[String]) {
        val List1 = List(21, 43, 54)
        val option1 = listToOption(List1)   
        
        println(option1)
        
        val List2 = List()
        
        val option2 = listToOption(List2)   
        
        println(option2)       
    }
}

Output:

输出:

Some(opt(List(21, 43, 54)))
None

Description:

描述:

In the above code, we have created two lists one empty(List2) and one with integer elements(List1). For converting the list to option, we have created a function named listToOption() which takes in a list and returns an option. Where we have used map and its method to check if the list is empty or not. If it is empty then the option will return None otherwise the list.

在上面的代码中,我们创建了两个列表,一个为空(List2) ,一个为整数(List1) 。 为了将列表转换为选项 ,我们创建了一个名为listToOption()的函数,该函数接收一个列表并返回一个option 。 我们使用map及其方法检查列表是否为空的地方。 如果为空,则该选项将返回None,否则返回列表

翻译自: https://www.includehelp.com/scala/convert-a-list-to-option.aspx

scala 转换为字符串

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值