sumit b sumit b - 1 month ago 9
Scala Question

Scala Array of different types of values

Writing a function in Scala that accepts an Array/Tuples/Seq of different types of values and sorts it based on first two values in each:

def sortFunction[T](input: Array[T]) = input(0)+ " " + input(1)


The input values I have are as below:

val data = Array((1, "alpha",88.9), (2, "alpha",77), (2, "beta"), (3, "alpha"), (1, "gamma",99))


Then I call the sortFunction as:

data.sortWith(sortFunction)


It is giving below errors:

- polymorphic expression cannot be instantiated to expected type; found : [T]scala.collection.mutable.Seq[T] ⇒ Int required: ((Int, String)) ⇒ ? Error occurred in an application involving default arguments.
- type mismatch; found : scala.collection.mutable.Seq[T] ⇒ Int required: ((Int, String)) ⇒ ? Error occurred in an application involving default arguments.


What am I doing wrong, or how do I get around this? I would be grateful for any suggestions.

Answer

If you know type of element in Array[T], you can use pattern matching (when same type). But If You don't know, Program can't decide how to sort your data.

One of methods is just String compare like below.

object Hello{
  def sortFunction[T](input1: T, input2: T) =
    input1 match {
      case t : Product =>
        val t2 = input2.asInstanceOf[Product]
        t.productElement(0).toString < t2.productElement(0).toString
      case v => input1.toString > input2.toString
    }
  def main(args: Array[String]): Unit = {


    val data = Array((1, "alpha",88.9), (2, "alpha",77), (2, "beta", 99), (3, "alpha"), (1, "gamma",99))

    println(data.sortWith(sortFunction).mkString)
  }
}

If you want to know Product tarit, see http://www.scala-lang.org/api/rc2/scala/Product.html