简体   繁体   English

具有2个泛型的scala方法,可以推断出一个

[英]scala method with 2 generics where one can be inferred

I'm new to Scala. 我是Scala的新手。 I am writing a method which sends a request of type RQ to a server, and receives a response of type Response[RSP]. 我正在编写一种方法,该方法将RQ类型的请求发送到服务器,并接收类型为Response [RSP]的响应。 The simplified version: I define a method to make a call: 简化版:我定义了一个进行调用的方法:

def invoke[RQ, RSP](request: RQ): Response[RSP] = {....}

When I invoke the method, all parameters can be inferred if I specify the type of the receiving variable, like this: 当我调用该方法时,如果我指定接收变量的类型,则可以推断所有参数,如下所示:

val result: Response[Double] = invoke("Hello")

But if I just say invoke("Hello") without assigning it to anything, it won't compile. 但是,如果我只说invoke("Hello")而不将其分配给任何东西,它将无法编译。 I have to supply the 2 generic types (eg invoke[String, Double]("Hello") ). 我必须提供2个泛型类型(例如invoke[String, Double]("Hello") )。 My question is: The String can be inferred from the parameter. 我的问题是:可以从参数推断出String。 Is there a way to write the call specifying only the RSP generic? 有没有一种方法可以编写仅指定RSP泛型的调用? Something in the lines of : invoke[ , Double]("Hello") ? 是否包含以下内容: invoke[ , Double]("Hello")

No. 没有。

This is a feature that has been asked about a number of times. 此功能已被询问了很多次。 Future versions of Scala may support a syntax similar to named arguments for methods: Scala的未来版本可能支持类似于方法命名参数的语法:

invoke[RSP = Double]("Hello")

At the moment, there is nothing much you can do except restructure your code so that the method has only one type parameter, and the second comes from the surrounding context. 目前,除了重组代码以使该方法仅具有一个类型参数,而第二种来自周围的上下文之外,您无能为力。

The more interesting question is: why do you even care about the return type if you just throw away the result anyway? 更为有趣的问题是:如果您只是丢弃结果,为什么还要关心返回类型? It looks like your method violates the Command-Query Separation Principle. 您的方法似乎违反了命令查询分离原则。 If your method simply returned Unit , you wouldn't need the second type parameter, and all would work fine. 如果您的方法仅返回Unit ,则不需要第二个类型参数,那么所有方法都可以正常工作。 If you actually used the return value, the type inferencer would at least have a chance to infer the second type parameter from the context. 如果您实际使用了返回值,则类型推断器将至少有机会从上下文中推断出第二个类型参数。 But the fact that you have a type parameter for the return value but ignore the return value means that there is no context for the type inferencer to look at. 但是,您具有用于返回值的类型参数但忽略了返回值的事实意味着,类型推断器没有要查看的上下文。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM