方法采用 Seq[T] 返回 String 而不是 Seq[Char] [英] Method taking Seq[T] to return String rather than Seq[Char]
问题描述
我想实现接受任意 Seq[T]
并返回 Seq[T]
的方法.但是当提供 String
时,它也应该返回 String
.
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
.
传递 String
由于从 String
到 WrappedString extends IndexedSeq[Char]
的一些隐式转换而起作用,但我得到 Seq[Char]
作为回报.是否有可能取回 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()
实现无关紧要,只是一个例子.
firstAndLast()
implementation is irrelevant, it is only an example.
推荐答案
是的,这是可能的.您必须要求其中一种花哨的 CanBuildFrom
s:
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.
这篇关于方法采用 Seq[T] 返回 String 而不是 Seq[Char]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!