Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Method taking Seq[T] to return String rather than Seq[Char]

I would like to implement method that takes arbitrary Seq[T] and returns Seq[T] as well. But when String is provided it should also return String.

Passing String works due to some implicit conversion from String to WrappedString extends IndexedSeq[Char], but I get Seq[Char] in return. Is it possible to get String back?

val sx: Seq[Int] = firstAndLast(List(1, 2, 3, 4))
val s1: Seq[Char] = firstAndLast("Foo Bar")
val s2: String = firstAndLast("Foo Bar")  //incompatible types error

def firstAndLast[T](seq: Seq[T]) = Seq(seq.head, seq.last)

firstAndLast() implementation is irrelevant, it is only an example.

like image 577
Tomasz Nurkiewicz Avatar asked May 21 '12 16:05

Tomasz Nurkiewicz


1 Answers

Yes, it is possible. You’ll have to require one of those fancy CanBuildFroms:

import scala.collection.generic.CanBuildFrom

def firstAndLast[CC, A, That](seq: CC)(implicit asSeq: CC => Seq[A], cbf: CanBuildFrom[CC, A, That]): That = {
  val b = cbf(seq)
  b.sizeHint(2)
  b += seq.head
  b += seq.last
  b.result
}

This will also work with arrays. Bonus: all lines in your example will compile and work as expected.

like image 150
Jean-Philippe Pellet Avatar answered Sep 22 '22 02:09

Jean-Philippe Pellet