简体   繁体   English

Scala-如何在类型的泛型子类型上调用方法?

[英]Scala - How to call a method on a generic subtype of a type?

A colleague wrote the following code: 一位同事编写了以下代码:

  def nonEmpty[Coll[_], T](implicit ev: Coll[T] <:< TraversableOnce[T]): Coll[T] => Boolean =
      (coll: Coll[T]) => coll.nonEmpty

The intent being to be able to call nonEmpty on any subtype of Traversable[T] . 目的是能够在Traversable[T]任何子类型上调用nonEmpty However, this feels overly complicated. 但是,这感觉太复杂了。 I am trying to simplify it, but with no luck so far. 我正在尝试简化它,但是到目前为止还没有运气。 I tried eg: 我试过例如:

def nonEmpty2[Coll[T] <:< TraversableOnce[T]](coll: Coll[T]): Boolean = coll.nonEmpty

But that is rejected with Wrong parameter on Coll[T] already. 但这已被Coll[T]上的Wrong parameter拒绝。 Is it just a syntactical (or series of, syntactical issues)? 它只是一个句法(或一系列的句法问题)吗? What is the simplest way to write that nonEmpty method? 编写该nonEmpty方法的最简单方法是什么?

There's no need to specify that you're dealing with a generic (higher-kinded) type that contains some other type. 无需指定您要处理的是包含其他类型的通用(高级)类型。 Just one type parameter is needed: 只需要一个类型参数:

def nonEmpty2[T](coll: T)(implicit ev: T <:< TraversableOnce[_]): Boolean = coll.nonEmpty

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM