什么时候在 Scala 中使用存在类型? [英] When to use existential type in Scala?

查看:57
本文介绍了什么时候在 Scala 中使用存在类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为方法提供以下内容:

def beCool[T <: S](args:Array[T]) = {}
def beCool(args:Array[T forSome {type T <:S}]) = {}

它们是等价的吗?你能举一些例子,什么时候应该选择哪个?

Are they equivalent? Can you give me some examples when should prefer which?

推荐答案

我认为,只要您需要访问 T,就需要第一个.最简单的例子是返回一个 args 元素:

You would need the first one, i think, whenever you need access to T. The simplest example is returning an element of args:

def beCool(args: Array[T forSome { type T }]): T = args.head // --> not found: type T
def beCool[T](args: Array[T]): T = args.head // ok

当您使用通配符时,第一个中不存在可访问类型 T 的情况更加明显:

the inexistance of an accessible type T in the first one is more apparent when you use the wildcard:

def beCool(args: Array[_ <: S]) = ???

这篇关于什么时候在 Scala 中使用存在类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆