Kostiantyn Palianychka
Kostiantyn Palianychka

Reputation: 595

Convert List[Any] to tuple with different type values

I trying convert List[Any] to tuple with some data types.

def matchValue(list: List[Any]):(Int, Int, Int, Option[String], String,Option[Date],String, Date,String, Option[Int],Option[String])= {
      list match {
        case i1::i2::i3::i4::i5::i6::i7::i8::i9::i10::i11 => (i1, i2, i3, i4, i5, i6, i7, i8, i9, i10, i11)
      }
    }

but i have error:

Expression of type Any doesn't conform to expected type Int

Upvotes: 0

Views: 404

Answers (2)

acidghost
acidghost

Reputation: 484

You could try to convert each value to its primitive type using x.asInstanceOf[T]. So for example x.asIntanceOf[Int] will convert any x to an Int.

Upvotes: 0

Alexey Romanov
Alexey Romanov

Reputation: 170713

You can write

case (i1: Int) :: (i2: Int) :: // etc
  1. If you have many similar cases with different target tuples, you indeed want something like shapeless (same tuple sizes can be handled).

  2. : Option[String] pattern can actually only check the argument is an Option. You'll get a warning about this, which can be ignored by using Option[String @unchecked], but it should only be done if you are sure you'll really get an Option[String].

Upvotes: 1

Related Questions