给出字符串:"A", "BDS", "DE", "BO", "IID"
这是我所拥有的:
def givenStrings(code: List[String]) = {
//val code = List("A", "BDS", "DE", "BO", "IID")
if (code.contains("A", "BDS"))
"It is in the first set";
else if(security_code.contains("DE", "BO", "IID"))
"It is in the second set";
else
"Not given";
}
givenStrings(List("A")) -> Should result in "It is in the first set"
givenStrings(List("DE")) -> Should result in "It is in the second set"
givenStrings(List("OOOOOO")) -> Should result in "Not given"
我得到的错误是
type mismatch;
found :String("A")
required: List[String]
答案 0 :(得分:1)
您编写的方法需要一个列表,但是您要传入一个字符串。因此,将您的方法签名更改为:
def givenStrings(code: String) = {
现在您将拥有一个期望字符串的方法,并且在给它一个字符串时不会抱怨。
现在,您也不想覆盖传递到函数中的代码的值。您应该删除该行。
最后,您不能只是开始调用变量security_code
。因此,将其更改回简单的code
。
答案 1 :(得分:0)
问题是您正在检查字符串是否包含列表,而所需的却相反。
我相信这更符合您的需求。
object Codes {
private val codes: Set[String] = Set("A", "BDS")
private val securityCodes: Set[String] = Set("DE", "BO", "IID")
def givenString(code: String): Unit = {
if (codes.contains(code)) {
println("It is in the first set")
} else if (securityCodes.contains(code)) {
println("It is in the second set")
} else {
println("Not given")
}
}
}