简体   繁体   English

Scala:具有泛型返回类型的函数

[英]Scala: having a function with generic return type

I have the following code which I am hoping to have a generic return type for my function: 我有以下代码,我希望我的函数具有泛型返回类型:

object myUtility {

  def myFunction(input1:String, input2:String, returnType: T): T = {

  :
  :
}

What should be the right syntax and what should I import in order to achieve this? 什么应该是正确的语法,我应该导入什么才能实现这一目标? Thank you very much! 非常感谢你!

You are not declaring that T is a type parameter on the method. 您没有声明T是该方法的类型参数。 You need to do that by adding [T] before the value parameter list: 您需要通过在值参数列表之前添加[T]来执行此操作:

def myFunction[T](input1:String, input2:String, returnType: T): T = ...

(Also, what's the parameter returnType for? You don't need that if your only intention with that was to declare the return type). (另外,参数returnType是什么?如果您的唯一意图是声明返回类型,那么您不需要它)。

In order to have a return value type that swaps out like that you need to use a type parameter. 为了获得一个类似于交换的返回值类型,您需要使用类型参数。 Something like... 就像是...

  def fxn[T](x : T) : T = {
    x
  }

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

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