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

≯℡__Kan透↙ 提交于 2019-12-12 09:34:35

问题


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:


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.



来源:https://stackoverflow.com/questions/10689161/method-taking-seqt-to-return-string-rather-than-seqchar

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!