hirofujitaaki hirofujitaaki - 7 months ago 95
Scala Question

Is there any concise way to convert the type from `Int` to `Double` after applying `splitAt` to a `List`?

My input is like this:

1 1 1 1 1 44 33


and the result I would like to get is like this:

val listA = List(1, 1, 1, 1, 1)
val listB = List(44.0, 33.0)


I know I can split a list using
splitAt
but I need the values of ListB to be the type of
Double
because I’m gonna use them in
/
operator.

so far my code is like this, and it’s ugly.

val (listA, listB) = li.splitAt(5)
val result = listA.sum * (listB(0).toDouble / (listB(0).toDouble + listB(1).toDouble))


Is there any better way to archive my wish?

Answer Source

You can map listB to contain Doubles:

val listBDouble = listB.map(_.toDouble)

After this you can use this in your expression:

val result = listA.sum * (listBDouble(0) / (listBDouble(0) + listBDouble(1)))

BTW, if you need having Doubles only because of the division, probably this is preferred:

 val result = listA.sum * ((listB(0): Double) / (listB(0) + listB(1)))

This way you ascribe (: Double) the nominator to be Double and the rest will work as expected.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download