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.
Yes, it is possible. You’ll have to require one of those fancy CanBuildFrom
s:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With