使用 _* 的可变参数的 Scala 类型归属导致错误 [英] Scala type ascription for varargs using _* cause error

查看:27
本文介绍了使用 _* 的可变参数的 Scala 类型归属导致错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 Scala 可变参数有一个基本的了解:接受可变参数的方法的参数需要提示它是一个使用 _* 的可变参数.使用Scala 2.10.3,我定义了以下两个方法

I have a rudimentary understanding of Scala varargs: that parameters to a method accepting varargs need to hint that it is a varargs using _*. Using Scala 2.10.3, I define the following two methods

scala> def method(varargs:Int*)(more:String*) = println(varargs,more)
method: (varargs: Int*)(more: String*)Unit
scala> val method2 = method(1,2,3)_
method2: Seq[String] => Unit = 

使用 List 或 Range 直接调用它们可以正常工作

Invoking them directly using a List or Range works fine

scala> val paramList = List("hi","ho")
paramList: List[java.lang.String] = List(hi, ho)

scala> method2(paramList)
(WrappedArray(1, 2, 3),List(hi, ho))

scala> val range = (1 to 5) map {_.toString}
range: scala.collection.immutable.IndexedSeq[String] = Vector(1, 2, 3, 4, 5)

scala> method2(range)
(WrappedArray(1, 2, 3),Vector(1, 2, 3, 4, 5))

为什么当我通过用 _* 分配参数来调用它们时,我得到错误?

Why is it when I invoke them by ascribing the parameter with _*, I get errors?

scala> method2(paramList:_*)
<console>:11: error: type mismatch;
 found   : List[String]
 required: Seq[Seq[String]]
              method2(paramList:_*)
                      ^

scala> method2(range:_*)
<console>:11: error: type mismatch;
 found   : scala.collection.immutable.IndexedSeq[String]
 required: Seq[Seq[String]]
              method2(range:_*)
                      ^

推荐答案

method2 不是一个接受重复参数的方法,它是一个带有 Seq[String].

method2 is not a method accepting repeated parameters, it's a function with a single parameter of type Seq[String].

你应该这样称呼它:method2(paramList) 没有 :_*.

You should call it like this: method2(paramList) without :_*.

scala 2.10中没有函数接受重复参数,但在scala 2.9中存在:

scala> def method(varargs:Int*)(more:String*) = println(varargs,more)
method: (varargs: Int*)(more: String*)Unit

scala> val method2 = method(1,2,3)_
method2: String* => Unit = <function1>

scala> val paramList = List("hi","ho")
paramList: List[java.lang.String] = List(hi, ho)

scala> method2(paramList:_*)
(WrappedArray(1, 2, 3),List(hi, ho))

注意method2的推断类型:Seq[String] =>2.10 中的单位 vs String* =>2.9 中的单元.

Note the inferred type of method2: Seq[String] => Unit in 2.10 vs String* => Unit in 2.9.

这不是一个有用的特性:你不能使用 String* => 类型的变量.Unit 作为参数或返回值.实际上 String* =>即使在 2.9 中,Unit 也不是有效类型:

It wasn't a useful feature: you can't use variable of type String* => Unit as a parameter or return value. Actually String* => Unit is not a valid type even in 2.9:

scala> def test(f: String* => Unit) = ()
<console>:1: error: ')' expected but '=>' found.
       def test(f: String* => Unit) = ()
                           ^

这篇关于使用 _* 的可变参数的 Scala 类型归属导致错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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