Scala方法无法解析变量

时间:2018-07-21 10:45:48

标签: scala

我刚开始使用Scala,并尝试编写一种从字符列表中删除一对括号的方法。

def removePairOfBrackets(chars: List[Char]): List[Char] =
  val firstOpeningBracket: Int = chars.indexOf('(')
  val firstClosingBracket: Int = chars.indexOf(')')
  if (firstOpeningBracket > firstClosingBracket) chars
  else
  chars.patch(firstOpeningBracket, Nil, 1).patch(firstClosingBracket - 1, Nil, 1)

在此方法的第二行中,我收到以下消息:

Cannot resolve symbol chars

2 个答案:

答案 0 :(得分:1)

该方法没有“ body”-固定大括号。

def removePairOfBrackets(chars: List[Char]): List[Char] = {
  val firstOpeningBracket: Int = chars.indexOf('(')
  val firstClosingBracket: Int = chars.indexOf(')')
  if (firstOpeningBracket > firstClosingBracket) chars
  else
    chars.patch(firstOpeningBracket, Nil, 1).patch(firstClosingBracket - 1, Nil, 1)
}

答案 1 :(得分:0)

Try this instead: 

  chars.mkString.replaceFirst("\\(","").replaceFirst("\\)","").toList

在Scala REPL中:

scala> val chars = List('a','b','(','c','(','d',')','e','(',')')
chars: List[Char] = List(a, b, (, c, (, d, ), e, (, ))

scala> chars.mkString.replaceFirst("\\(","").replaceFirst("\\)","").toList
res10: List[Char] = List(a, b, c, (, d, e, (, ))

scala>