0

I have the following value:

val x = List((("Burger and chips",4.99),4.99,1), (("Pasta & Chicken with Salad",8.99), 8.99,2), (("Rice & Chicken with Chips",8.99), 8.99,2))

after printing I get this:

x.foreach(x => println(x._3 + " x " + x._1 +"\t\t\t\t"+"$"+x._2 * x._3 ))

1 x (Burger and chips,4.99)             $4.99
2 x (Pasta & Chicken with Salad,8.99)               $17.98
2 x (Rice & Chicken with Chips,8.99)                $17.98

However i want this result instead:

1 x (Burger and chips,4.99)                         $4.99
2 x (Pasta & Chicken with Salad,8.99)               $17.98
2 x (Rice & Chicken with Chips,8.99)                $17.98

I know the text size is causing the problem but is there a way around it??

Thanks

mike
  • 35
  • 6
  • Is [this answer](https://stackoverflow.com/questions/15375231/how-do-i-format-a-string-with-string-interpolation-in-scala-as-a-fixed-width-str) sufficient? Additional hint: `${x._1}%-40s` would make it left-aligned. And by the way: `\t` are a pest. – Andrey Tyukin Jul 18 '18 at 18:23

1 Answers1

2

Scala's "f interpolator" is useful for this:

x.foreach { 
  case (text, price, amount) => println(f"$amount x $text%-40s $$${price*amount}") 
}

// prints:
1 x (Burger and chips,4.99)                  $4.99
2 x (Pasta & Chicken with Salad,8.99)        $17.98
2 x (Rice & Chicken with Chips,8.99)         $17.98
Tzach Zohar
  • 37,442
  • 3
  • 79
  • 85
  • In OP's code, the tuple occupies 48 characters. The 40 must be just a strange coincidence ;) – Andrey Tyukin Jul 18 '18 at 18:31
  • 1
    honestly - it is! I started with 20 and just added 10 until it looked nice... (classic developer). Then I saw your comment and decided to keep it, assuming you must know what you're talking about ;) – Tzach Zohar Jul 18 '18 at 18:35
  • 1
    Isn't it hilarious that `Rice & Chicken with Chips` can be parsed as a valid type in Dotty...? – Andrey Tyukin Jul 18 '18 at 18:42