12

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.

1 Answer 1

15

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.

10
  • I'm pretty sure it won't work with Arrays; you have no manifest defined May 21, 2012 at 18:06
  • 2
    It does work, because the needed ClassManifest is provided implicitly to the method delivering the appropriate CanBuildFrom, scala.Array.canBuildFrom. May 21, 2012 at 18:22
  • 2
    This should be easier with Miles' FromRepr, I guess. May 21, 2012 at 19:07
  • 3
    @DanielC.Sobral Sounds interesting; how about an example? May 21, 2012 at 20:04
  • 2
    @Jean-Philippe, thanks for your answer and the follow up comment. I was provoked into trying to find where the implicits for asSeq came from and discovered the following command Ctrl+Shift+P on IntelliJ which presents the actual implicit parameters at a call site. May 21, 2012 at 20:34

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.