forall in Scala

后端 未结 5 1886
别那么骄傲
别那么骄傲 2020-12-02 05:57

As shown below, in Haskell, it\'s possible to store in a list values with heterogeneous types with certain context bounds on them:

data ShowBox = forall s. S         


        
5条回答
  •  时光说笑
    2020-12-02 06:49

    I don't think a 1-to-1 translation from Haskell to Scala is possible here. But why don't you want to use subtyping? If the types you want to use (such as Int) lack a show method, you can still add this via implicit conversions.

    scala> trait Showable { def show:String }
    defined trait Showable
    
    scala> implicit def showableInt(i:Int) = new Showable{ def show = i.toString }
    showableInt: (i: Int)java.lang.Object with Showable
    
    scala> val l:List[Showable] = 1::Nil
    l: List[Showable] = List($anon$1@179c0a7)
    
    scala> l.map(_.show)
    res0: List[String] = List(1)
    

提交回复
热议问题