1

I need to do a char conversion like this: accountNumber => ACCOUNT_NUMBER

Where there is a caps letter, then prefix a underscore. If not, just capitalize the character

I tried like below

scala> "accountNumber".map{ x => x match { case x if x == x.toUpper => "_"+x ; case x if x!= x.toUpper => x.toUpper}}.mkString
res38: String = ACCOUNT_NUMBER 

It works, but it works differently when there is a digit in between.

scala> "filler51".map{ x => x match { case x if x == x.toUpper && x.isDigit && true => "_"+x ; case x if x!= x.toUpper => x.toUpper}}.mkString 
res31: String = FILLER_5_1

I'm expecting it to print FILLER51. For this, I tweaked the code as below, but I'm getting an error.

 scala> "filler51".map{ x => x match { case x if x == x.toUpper && !(x.isDigit)   => "_"+x ; case x if x!= x.toUpper => x.toUpper}}.mkString  
scala.MatchError: 5 (of class java.lang.Character)
  at .$line40$$read$$$anonfun$1(<console>:12)
  at .$line40$$read$$$anonfun$1$adapted(<console>:12)
  at $$Lambda$1399/645018917.apply(Unknown Source)
  at ap(StringOps.scala:29)
     ... 28 elided
jwvh
  • 50,871
  • 7
  • 38
  • 64
stack0114106
  • 8,534
  • 3
  • 13
  • 38

3 Answers3

1

You're almost there – just need a catch-all to cover all cases, as your two match cases have not exhausted all possibilities (namely, the case of isDigit):

"thisFiller51".map { x => x match { 
  case x if x == x.toUpper && !x.isDigit => "_" + x
  case x if x != x.toUpper => x.toUpper
  case x => x
} }.mkString  
// res1: String = THIS_FILLER51
Leo C
  • 22,006
  • 3
  • 26
  • 39
0

Please use the below approach

scala> "filler51".map(x=>if(x>='A' && x<='Z') '_'.toString+x.toString else x.toString)
                 .mkString
                 .toUpperCase

Result:

res6: String = FILLER51
The Archetypal Paul
  • 41,321
  • 20
  • 104
  • 134
Manoj Kumar Dhakad
  • 1,862
  • 1
  • 12
  • 26
0

Instead of testing for != upper, test for explicitly lower:

"filler51".map {x => x match {case x if x == x.toUpper && !(x.isDigit) => "_" + x; case x if x == x.toLower => x.toUpper}}.mkString
user unknown
  • 35,537
  • 11
  • 75
  • 121