语法糖:_* 用于将 Seq 视为方法参数 [英] Syntax sugar: _* for treating Seq as method parameters

查看:44
本文介绍了语法糖:_* 用于将 Seq 视为方法参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚在网络上的某个地方注意到了这个结构:

I just noticed this construct somewhere on web:

val list = List(someCollection: _*)

_* 是什么意思?这是某些方法调用的语法糖吗?我的自定义类应该满足哪些约束才能利用这种语法糖?

What does _* mean? Is this a syntax sugar for some method call? What constraints should my custom class satisfy so that it can take advantage of this syntax sugar?

推荐答案

通常,: 表示法用于类型归属,强制编译器将值视为某种特定类型.这与铸造完全不一样.

Generally, the : notation is used for type ascription, forcing the compiler to see a value as some particular type. This is not quite the same as casting.

val b = 1 : Byte
val f = 1 : Float
val d = 1 : Double

在这种情况下,您将归因于特殊的 varargs 类型.这反映了用于声明 varargs 参数的星号符号,可用于任何类型的子类 Seq[T] 的变量:

In this case, you're ascribing the special varargs type. This mirrors the asterisk notation used for declaring a varargs parameter and can be used on a variable of any type that subclasses Seq[T]:

def f(args: String*) = ... //varargs parameter, use as an Array[String]
val list = List("a", "b", "c")
f(list : _*)

这篇关于语法糖:_* 用于将 Seq 视为方法参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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