Scala:方法重载泛型类型

Mig*_*dez 11 generics scala manifest reification

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

// 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});
  }
}
Run Code Online (Sandbox Code Playgroud)

但是,如果我尝试在Scala中执行相同操作,则会引发编译时错误,List[Int]List[Double]由于擦除而擦除到相同类型.我听说Scala Manifest可以用来解决这个问题,但我不知道怎么做.我也没有在文档中找到任何有用的东西.

所以我的问题是:我如何使用Manifests(或其他任何有效的方法)重载方法而不是因擦除而擦除到相同类型的泛型类型?

Ken*_*oom 22

由于擦除后那些将具有相同类型,因此清单不会真正帮助.

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

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)
}
Run Code Online (Sandbox Code Playgroud)


Rap*_*ael 10

你不会像Scala那样做.为什么尝试模拟在JVM限制下永远无法正常工作的东西?尝试惯用Scala:

trait Fooable[T] {
  def foo : Unit
}

object IntListFoo extends Fooable[List[Int]] {
  def foo {
    println("I just print")
  }
}

class DoubleListFoo(val l : List[Double]) extends Fooable[List[Double]] {
  def foo {
    println("I iterate over list and print it.")
    l.foreach { e =>
      println(e)
    }
  }
}

implicit def intlist2fooable(l : List[Int]) = IntListFoo
implicit def doublelist2fooable(l : List[Double]) = new DoubleListFoo(l)
Run Code Online (Sandbox Code Playgroud)

然后,您可以执行类似的代码

List(1,2,3,4).foo
List(1.0,2.0,3.0).foo
Run Code Online (Sandbox Code Playgroud)