Scala类型语法 [英] Scala Type Syntax

查看:91
本文介绍了Scala类型语法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我观察到,如果我想创建一个可以接受任何类型列表并返回布尔值的泛型函数,那么我可以使用以下语法来进行函数声明:

  def someFunction [A](l:List [A]):Boolean 

然而,我可以用这个语法实现一个等价的函数声明:

  def someFunction (l:List [_]):布尔

后面的语法对我来说很有意义;下划线表示任何类型的List的通配符。然而前者令人困惑;这两种语法之间的语义差异是什么?注意:我注意到在第一个语法示例中,我可以使用[B]或[c]甚至[%]代替[A]。

解决方案

A 是一个类型参数。就像一个值参数,比如你的 l 传递参数,它就是某个类型的名称或占位符,它可能在不同的时间是不同的。在这个例子中, A 没有被使用,所以,是的,使用<$ <

c $ c> _ 更有意义并且更清晰,但是如果要从列表中返回一个元素,那么方法返回类型将是 A (或任何你想给这个参数的名字)。使用 _ 作为返回类型没有任何意义。


I've observed that, if I want to make a generic function that can accept a list of any type and return a boolean, I can use the following syntax for a function declaration:

def someFunction[A](l:List[A]):Boolean

However, I can achieve an equivalent function declaration with this syntax as well:

def someFunction(l:List[_]):Boolean

The latter syntax makes sense to me; the underscore indicates a wildcard for a List of any type. However the former is confusing; what's the semantic difference between the two types of syntax, if there is one at all? Note: I noticed I could use [B] or [c] or even [%] in place of the "[A]" in the first syntax example.

解决方案

The A is a "type parameter". Just like a value parameter, such as your l passed parameter, it is the "name", or place holder, for a some type which might be different at different times (i.e. with different invocations of the method).

In your example the A is unused so, yeah, using _ makes more sense and is clearer, but if you were to return an element from the list then the method return type would be A (or whatever name you want to give that parameter). Using _ as a return type wouldn't make any sense.

这篇关于Scala类型语法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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