6

Trying to convert few of my C# project into Scala, and still trying to figure out how do to some of the conversion. I came across this code and would appreciate if someone can help me to write below code in Scala, i m particularly interested in anonymous code block in Select statement.

static void Main(string[] args)
{
  Stock stk = new Stock();
  Select(stk, a => new { a.Prices, a.Symbol });
}
public static U Select<T, U>(T data,Func<T,U> item)
{
  return item(data);
}
GammaVega
  • 779
  • 1
  • 7
  • 23

2 Answers2

9

Here's one implementation.

class Stock(val prices: List[Double], val symbol: String) 

object CSharp {
  def select[T, U](data: T)(f: T => U): U = {
    f(data);
  }  
  def main(args: Array[String]): Unit = {
    val stk = new Stock(List(1.1, 2.2, 3.3, 4.4), "msft")
    select(stk)(a => (a.prices, a.symbol) );
  }
}
Ben Kyrlach
  • 379
  • 1
  • 5
6

It will be a little wordier and less performant (cause scala will use reflection for doing such nasty things):

def select[T, U](data: T, item: T => U) = item(data)
case class Stock(price: Int, symbol: String)


val x = select(
  Stock(100, "AAPL"), 
  { stock: Stock => new { val price = stock.price; val symbol = stock.symbol }}
)

x.symbol
res2: String = AAPL

In general you should prefer tuples (Ben's answer) or case classes.

Community
  • 1
  • 1
om-nom-nom
  • 62,329
  • 13
  • 183
  • 228