Scala: Method overloading over generic types

前端 未结 3 1334
夕颜
夕颜 2020-12-31 11:12

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;

publ         


        
3条回答
  •  失恋的感觉
    2020-12-31 11:43

    You would not do it like that in Scala. Why try to emulate something that can never work properly given JVM restrictions? Try idiomatic Scala instead:

    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)
    

    Then, you can execute code like

    List(1,2,3,4).foo
    List(1.0,2.0,3.0).foo
    

提交回复
热议问题