[英]scala: how to create a generic type which is subtype of all the number classes in scala so that it can include compare method
[英]Scala - How to call a method on a generic subtype of a type?
一位同事编写了以下代码:
def nonEmpty[Coll[_], T](implicit ev: Coll[T] <:< TraversableOnce[T]): Coll[T] => Boolean =
(coll: Coll[T]) => coll.nonEmpty
目的是能够在Traversable[T]
任何子类型上调用nonEmpty
。 但是,这感觉太复杂了。 我正在尝试简化它,但是到目前为止还没有运气。 我试过例如:
def nonEmpty2[Coll[T] <:< TraversableOnce[T]](coll: Coll[T]): Boolean = coll.nonEmpty
但这已被Coll[T]
上的Wrong parameter
拒绝。 它只是一个句法(或一系列的句法问题)吗? 编写该nonEmpty
方法的最简单方法是什么?
无需指定您要处理的是包含其他类型的通用(高级)类型。 只需要一个类型参数:
def nonEmpty2[T](coll: T)(implicit ev: T <:< TraversableOnce[_]): Boolean = coll.nonEmpty
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.