gpt4 book ai didi

scala - 在Scala中将空字符串转换为None

转载 作者:行者123 更新时间:2023-12-01 09:55:40 27 4
gpt4 key购买 nike

我需要将两条可能为空的地址线连接成一条(两行之间有一个空格),但是如果两条地址线均为None(此字段将进入None变量),我需要它返回Option[String]。以下命令让我了解所需的串联方式:

Seq(myobj.address1, myobj.address2).flatten.mkString(" ")

但这给了我一个空字符串,而不是 None,如果address1和address2都是 None

最佳答案

好吧,在Scala中,存在Option[ T ]类型,该类型旨在消除由于null而导致的各种运行时问题。

所以...这是您使用选项的方式,因此基本上Option[ T ]可以具有两种类型的值之一-Some[ T ]None

// A nice string
var niceStr = "I am a nice String"

// A nice String option
var noceStrOption: Option[ String ] = Some( niceStr )

// A None option
var noneStrOption: Option[ String ] = None

现在来解决您的问题:
// lets say both of your myobj.address1 and myobj.address2 were normal Strings... then you would not have needed to flatten them... this would have worked..
var yourString = Seq(myobj.address1, myobj.address2).mkString(" ")

// But since both of them were Option[ String ] you had to flatten the Sequence[ Option[ String ] ] to become a Sequence[ String ]
var yourString = Seq(myobj.address1, myobj.address2).flatten.mkString(" ")

//So... what really happens when you flatten a Sequence[ Option[ String ] ] ?

// Lets say we have Sequence[ Option [ String ] ], like this
var seqOfStringOptions = Seq( Some( "dsf" ), None, Some( "sdf" ) )

print( seqOfStringOptions )
// List( Some(dsf), None, Some(sdf))

//Now... lets flatten it out...
var flatSeqOfStrings = seqOfStringOptions.flatten

print( flatSeqOfStrings )
// List( dsf, sdf )

// So... basically all those Option[ String ] which were None are ignored and only Some[ String ] are converted to Strings.

// So... that means if both address1 and address2 were None... your flattened list would be empty.

// Now what happens when we create a String out of an empty list of Strings...

var emptyStringList: List[ String ] = List()
var stringFromEmptyList = emptyStringList.mkString( " " )
print( stringFromEmptyList )
// ""
// So... you get an empty String

// Which means we are sure that yourString will always be a String... though it can be empty (ie - "").

// Now that we are sure that yourString will alwyas be a String, we can use pattern matching to get out Option[ String ] .

// Getting an appropriate Option for yourString
var yourRequiredOption: Option[ String ] = yourString match {
// In case yourString is "" give None.
case "" => None
// If case your string is not "" give Some[ yourString ]
case someStringVal => Some( someStringVal )
}

关于scala - 在Scala中将空字符串转换为None,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28331983/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com