小编Mig*_*dez的帖子

Scala:方法重载泛型类型

在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(或其他任何有效的方法)重载方法而不是因擦除而擦除到相同类型的泛型类型?

generics scala manifest reification

11
推荐指数
2
解决办法
3278
查看次数

从数组到列表的隐式转换

如何编写隐式转换Array[_]List[_]类型?我尝试了以下但它似乎不起作用.

scala> implicit def arrayToList[A : ClassManifest](a: Array[A]): List[A] = a.toList
<console>:5: error: type mismatch;
 found   : Array[A]
 required: ?{val toList: ?}
Note that implicit conversions are not applicable because they are ambiguous:
 both method arrayToList in object $iw of type [A](a: Array[A])(implicit evidence$1: ClassManifest[A])List[A]
 and method genericArrayOps in object Predef of type [T](xs: Array[T])scala.collection.mutable.ArrayOps[T]
 are possible conversion functions from Array[A] to ?{val toList: ?}
       implicit def arrayToList[A : ClassManifest](a: Array[A]): List[A] = a.toList
                                                                           ^
Run Code Online (Sandbox Code Playgroud)

scala implicit-conversion

7
推荐指数
2
解决办法
2万
查看次数