开发者

When to use existential type in Scala?

开发者 https://www.devze.com 2023-02-18 20:30 出处:网络
Give the following to methods: def beCool[T <: S](args:Array[T]) = {} def beCool(args:Array[T forSome {type T <:S}]) = {}

Give the following to methods:

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?


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

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

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

精彩评论

暂无评论...
验证码 换一张
取 消