我想在scala中检查空字符串。如果字符串为空,则返回一个选项,否则返回None
更新1
case class Student(name:String,subject:Symbol = Symbol("Default")))
def getStudentName(name :Option[String]):Option[Student]={
name.flatMap(_ => Option(Student(name.get)))
}
更新2
情景1:
call 1- print(getStudentName(Option("abc")))//Some(Student(abc))
Call 2- print(getStudentName(Option("")))//return Some(Student())
情景2:
case class Emp(id:Int)
def getEmp(id:Option[String]):Option[Emp]={
id.flatMap(_ => Option(Emp(id.get.toInt)))
}
print(getEmp(Option("123")))
print(getEmp(Option("")))//gives number format exception
我想通过None
""
答案 0 :(得分:3)
Option
正在进行包装过多,您可以轻松完成:
情景1:
name
.filterNot(_.isEmpty)
.map(Student(_))
Scenaro 2:
id
.filterNot(_.isEmpty)
.filter(_.matches("^[0-9]*$")) // ensure it's a number so .toInt is safe
.map(id => Emp(id.toInt))