了解Seq [AnyVal]和Seq [String]的混合上下文界限 [英] Understanding Mixed Context Bounds of Seq[AnyVal] and Seq[String]
本文介绍了了解Seq [AnyVal]和Seq [String]的混合上下文界限的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
假设我有一些函数应该采用一个整数序列或一个字符串序列.
Suppose I have some function that should take a sequence of Ints or a sequence of Strings.
我的尝试:
object Example extends App {
import scala.util.Random
val rand: Random.type = scala.util.Random
// raw data
val x = Seq(1, 2, 3, 4, 5).map(e => e + rand.nextDouble())
val y = Seq("chc", "asas")
def f1[T <: AnyVal](seq: Seq[T]) = {
println(seq(0))
}
// this works fine as expected
f1(x)
// how can i combine
f1(y)
}
如何添加它以便也可以使用字符串?
How can I add this to also work with strings?
如果我将方法签名更改为:
If I change the method signature to:
def f1[T <: AnyVal:String](seq: Seq[T])
但是这行不通.
有没有一种方法可以对类型强加我所需的约束?
Is there a way to impose my required constraint on the types elegantly?
推荐答案
请注意上限
A <: C
和 上下文绑定
A : C
所以类型参数子句[T <: AnyVal : String]
没有多大意义.同样,诸如String
之类的类型很少(或从不)用作上下文边界.
so type parameter clause [T <: AnyVal : String]
does not make much sense. Also types such as String
are rarely (or never) used as context bounds.
这是类型类方法
trait EitherStringOrAnyVal[T]
object EitherStringOrAnyVal {
implicit val str: EitherStringOrAnyVal[String] = new EitherStringOrAnyVal[String] {}
implicit def aval[T <: AnyVal]: EitherStringOrAnyVal[T] = new EitherStringOrAnyVal[T] {}
}
def f1[T: EitherStringOrAnyVal](seq: Seq[T]): Unit = {
println(seq(0))
}
f1(Seq(1)) // ok
f1(Seq("a")) // ok
f1(Seq(Seq(1))) // nok
或通用类型约束方法
object Foo {
private def impl[T](seq: Seq[T]): Unit = {
println(seq(0))
}
def f1[T](seq: Seq[T])(implicit ev: T =:= String): Unit = impl(seq)
def f1[T <: AnyVal](seq: Seq[T]): Unit = impl(seq)
}
import Foo._
f1(Seq(1)) // ok
f1(Seq("a")) // ok
f1(Seq(Seq(1))) // nok
这篇关于了解Seq [AnyVal]和Seq [String]的混合上下文界限的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文