How do I setup multiple ORed type bounds in Scala

后端 未结 4 1196
难免孤独
难免孤独 2020-12-16 18:43

Is it possible to do something like this in Scala:

class MyTest {
   def foo[A <: String _or_ A <: Int](p:List[A]) =  {} 
}

That is,

4条回答
  •  死守一世寂寞
    2020-12-16 19:06

    There is this hack:

    implicit val x: Int = 0
    def foo(a: List[Int])(implicit ignore: Int) { }
    
    implicit val y = ""
    def foo(a: List[String])(implicit ignore: String) { }
    
    foo(1::2::Nil)
    foo("a"::"b"::Nil)
    

    See http://michid.wordpress.com/2010/06/14/working-around-type-erasure-ambiguities-scala/

    And also this question.

提交回复
热议问题