我想实现任意的方法Seq[T]
并返回Seq[T]
以及。但当String
如果它也应该返回String
.
Passing String
由于一些隐式转换而起作用String
to WrappedString extends IndexedSeq[Char]
,但我得到Seq[Char]
作为回报。是否可以得到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()
实施无关紧要,它只是一个例子。
对的,这是可能的。你必须需要其中之一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
}
这也适用于数组。奖励:示例中的所有行都将按预期进行编译和工作。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)