2
votes

I'm new to Scala. I have a function:

def fromBinaryListBig(in: Array[Int]): BigInt = {
  var sum = 0
  in foreach (x => {sum <<= 1; sum += (x&1)})
  sum
}

Is it possible to make the return type generic (integer types, Long, Int)? Thanks in advance ...

2

2 Answers

2
votes

You can have a generic return type if it matches a generic parameter ...

def fromBinaryListBig[N:Numeric](in: Array[N]): N = in.sum

... but you can't get different (generic) return types based on some internal condition (such as the value of an accumulated sum, for example).

0
votes

Technically, yes, it's quite possible:

def fromBinaryListBig[A](in: Array[Int])(implicit ev: Integral[A]): A = {
  var sum = ev.zero
  val two = ev.fromInt(2)
  in foreach (x => {sum *= two; sum += ev.fromInt(x&1)})
  sum
}

This means the caller determines the return type, so they can write e.g.

val x = fromBinaryListBig[Byte](Array(0, 1, 0, 1, 0, 0, 0))

or specify the expected type

val x: BigInt = fromBinaryListBig(...)