简体   繁体   English

类型类的scala存在类型

[英]scala existence type of type class

I want to define a function like this 我想定义一个这样的功能

def showList(items: Seq[_ : Show]) = {...} type parameter of Seq is any type that has an context bound Show def showList(items: Seq[_ : Show]) = {...} Seq type参数是任何具有上下文绑定Show

Thus I could call showList(Seq(1, "abc")) . 因此,我可以调用showList(Seq(1, "abc"))

How should declare the method ? 应该如何声明该方法?

def showList[A: Show](items: Seq[A]) = { ... }

or more explicitly (with the advantage of having the type class instance directly available) 或更明确地(具有直接使用类型类实例的优势)

def showList[A](items: Seq[A])(implicit ev: Show[A]) = { ... }

For the specific case, since scala collections are monomorphic, you'll need a Show[Any] instance. 对于特定情况,由于scala集合是单态的,因此需要Show[Any]实例。

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

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