在scala varargs中强制单个参数 [英] Force single argument in scala varargs

查看:115
本文介绍了在scala varargs中强制单个参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个带有两个方法的Java类(取自mockito):

Given a java class with two methods (taken from mockito):

OngoingStubbing<T> thenReturn(T value);

OngoingStubbing<T> thenReturn(T value, T... values);

如果我使用以下命令从scala调用

If I invoke from scala with

....thenReturn("something")

我得到一个错误:

Description Resource    Path    Location    Type
ambiguous reference to overloaded definition, both method thenReturn in trait OngoingStubbing of type (x$1: java.lang.Object, x$2: <repeated...>[java.lang.Object])org.mockito.stubbing.OngoingStubbing[java.lang.Object] and  method thenReturn in trait OngoingStubbing of type (x$1: java.lang.Object)org.mockito.stubbing.OngoingStubbing[java.lang.Object] match argument types (java.lang.String)

我不知道如何解决此问题.

And I cannot figure out how to fix this.

推荐答案

这些答案都是针对错误问题的.差异是细微的,但这与链接票证中的问题不同.那确实需要不合理的体操来调用non-varargs方法.对于这一点,下面的内容就足够了.

These answers are all to the wrong question. The difference is subtle, but this is not the same issue as the one in the linked ticket. That one does require unreasonable gymnastics to call the non-varargs method. For this one, the following is enough.

thenReturn[String]("something")

或者,如果由于某些原因您不想这样做,则不需要类型别名和强制类型转换.您可以直接使用结构类型归属.

Or, if you didn't want to do that for some reason, you don't need the type alias and the cast. You can use a structural type ascription directly.

(this: { def thenReturn[T](s: T): OngoingStubbing[T] }).thenReturn("something")

这里的问题是重载和多态相交处的类型推断-一种方法更具体,但是scalac不能弄清楚哪种方法. SI-2991中的问题是真正的模棱两可,这是由于重载和元组转换之间的相互作用所致-两者都不是更具体.

The issue here is type inference at the intersection of overloading and polymorphism - one method is more specific, but scalac doesn't figure out which. The issue in SI-2991 is genuine ambiguity due to an interaction between overloading and tuple conversion - neither is more specific.

这篇关于在scala varargs中强制单个参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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