Scala:方法重载泛型类型 [英] Scala: Method overloading over generic types

查看:122
本文介绍了Scala:方法重载泛型类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在C#中,我可以在泛型类型上重载方法,如下例所示:

  // http:// ideone .com / QVooD 
使用System;
使用System.Collections.Generic;

public class Test {
public static void Foo(List< int> int){
Console.WriteLine(I just print);


public static void Foo(List< double> doubles){
Console.WriteLine(我迭代列表并打印它。);
foreach(双倍变量x)
Console.WriteLine(x);


public static void Main(string [] args){
Foo(new List< int> {1,2});
Foo(新列表< double> {3.4,1.2});






$ b

然而,如果我尝试在Scala中做同样的事情,它会产生一个编译时错误: List [Int] List [Double] 擦除。我听说Scala的 Manifest s可以用来解决这个问题,但我不知道如何。我也没有在文档中找到任何有用的东西。所以我的问题是:如何使用 Manifest s(或其他任何可行的方法)来重载方法泛型类型由于擦除而被擦除成相同类型?

解决方案

Manifest不会真的有帮助,因为那些会有相同的擦除后输入。



什么将有助于获得不同数量的参数(或擦除后的不同类型)。我发现有不同数量的隐式参数可以透明地解决这个问题,并且通过使用 scala.Predef.DummyImplicit ,您甚至不必在任何地方导入隐式。

  class Test {
def foo(ints:List [Int])
def foo(doubles:List [ Double])(隐式i1:DummyImplicit)
def foo(字符串:List [字符串])(隐式i1:DummyImplicit,i2:DummyImplicit)
}


In C# I can overload methods on generic type as shown in the example below:

// http://ideone.com/QVooD
using System;
using System.Collections.Generic;

public class Test {
  public static void Foo(List<int> ints) {
    Console.WriteLine("I just print");
  }

  public static void Foo(List<double> doubles) {
    Console.WriteLine("I iterate over list and print it.");
    foreach(var x in doubles)
      Console.WriteLine(x);
  }

  public static void Main(string[] args) {
    Foo(new List<int> {1, 2});
    Foo(new List<double> {3.4, 1.2});
  }
}

However if I try to do the same in Scala, it will raise a compile time error that List[Int] and List[Double] erase to the same type due to erasure. I heard Scala's Manifests can be used to work around this, but I don't know how. I didn't find anything helpful in the docs either.

So my question is: How do I use Manifests (or whatever else that works) to overload methods over generic types that erase to same type due to erasure?

解决方案

The Manifest won't really help either becuase those will have the same type after erasure.

What will help having different numbers of arguments (or different types after erasure). I find having different numbers of implicit arguments can transparently solve this problem, and by using scala.Predef.DummyImplicit, you don't even have to import an implicit anywhere.

class Test{
  def foo(ints : List[Int])
  def foo(doubles : List[Double])(implicit i1:DummyImplicit)
  def foo(strings : List[String])(implicit i1:DummyImplicit, i2:DummyImplicit)
}

这篇关于Scala:方法重载泛型类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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