This page is no longer maintained — Please continue to the home page at www.scala-lang.org

Better way to write this?

3 replies
nilskp
Joined: 2009-01-30,
User offline. Last seen 1 year 27 weeks ago.
I feel like there is a slightly shorter way to write the foreach part, but I can't recall:
val list = 1 :: 2L :: 3d :: Nil
list.foreach { n =>  n match {    case i: Int => println("Int: " + i)     case l: Long => println("Long: " + l)    case d: Double => println("Double: " + d)     case _ => println("Unknown: " + n)  }}

Derek Williams 3
Joined: 2011-08-12,
User offline. Last seen 42 years 45 weeks ago.
Re: Better way to write this?
On Fri, Jan 13, 2012 at 5:11 PM, Nils Kilden-Pedersen <nilskp [at] gmail [dot] com> wrote:
I feel like there is a slightly shorter way to write the foreach part, but I can't recall:
val list = 1 :: 2L :: 3d :: Nil
list.foreach { n =>  n match {    case i: Int => println("Int: " + i)     case l: Long => println("Long: " + l)    case d: Double => println("Double: " + d)     case _ => println("Unknown: " + n)  }}


You should be able to drop the match part:
list foreach {  case i: Int => println("Int: " + i)   case l: Long => println("Long: " + l)  case d: Double => println("Double: " + d)   case n => println("Unknown: " + n)}


--
Derek Williams
nilskp
Joined: 2009-01-30,
User offline. Last seen 1 year 27 weeks ago.
Re: Better way to write this?
On Fri, Jan 13, 2012 at 6:17 PM, Derek Williams <derek [at] fyrie [dot] net> wrote:

You should be able to drop the match part:

Yes, of course. It felt wrong, and it was. 
Thanks!
vpatryshev
Joined: 2009-02-16,
User offline. Last seen 1 year 24 weeks ago.
Re: Better way to write this?
Omg something new again... and beautiful too


On Fri, Jan 13, 2012 at 4:17 PM, Derek Williams <derek [at] fyrie [dot] net> wrote:
On Fri, Jan 13, 2012 at 5:11 PM, Nils Kilden-Pedersen <nilskp [at] gmail [dot] com> wrote:
I feel like there is a slightly shorter way to write the foreach part, but I can't recall:
val list = 1 :: 2L :: 3d :: Nil
list.foreach { n =>  n match {    case i: Int => println("Int: " + i)     case l: Long => println("Long: " + l)    case d: Double => println("Double: " + d)     case _ => println("Unknown: " + n)  }}


You should be able to drop the match part:
list foreach {  case i: Int => println("Int: " + i)   case l: Long => println("Long: " + l)  case d: Double => println("Double: " + d)   case n => println("Unknown: " + n)}


--
Derek Williams

Copyright © 2012 École Polytechnique Fédérale de Lausanne (EPFL), Lausanne, Switzerland