pwwolff
pwwolff

Reputation: 626

Scala method cannot resolve variable

I'm just getting started with Scala and trying to write a method that removes a pair of parentheses from a list of characters.

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)

In the second line of this method I get the message that:

Cannot resolve symbol chars

Upvotes: 0

Views: 367

Answers (2)

RAGHHURAAMM
RAGHHURAAMM

Reputation: 1099

Try this instead: 

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

In 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>

Upvotes: 0

pwwolff
pwwolff

Reputation: 626

The method had no 'body' - adding curly brackets fixed it.

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)
}

Upvotes: 1

Related Questions