Is it possible to find a common supertype on type-system level in Scala?

前端 未结 3 1478
梦谈多话
梦谈多话 2020-12-19 02:53

Is it possible to make a type-alias (or something equivalent) in Scala that takes two parameters and returns their common supertype? In other words, I\'m trying to find some

3条回答
  •  南笙
    南笙 (楼主)
    2020-12-19 03:37

    (Not a complete solution, but might give some ideas)

    One impressive feature of Scala is its ability to return a list of Fruits when an orange is appended to a list of apples. It's fine with values, precisely because you let the generic type be inferred.

    import scala.reflect.Manifest
    
    def CommonSuperType[A, B >: A : Manifest](a:A, b:B) = manifest[B]  
    

    It works (kind of) :

    scala> CommonSuperType(new JButton, new JPanel)
    res42: Manifest[javax.swing.JComponent with javax.accessibility.Accessible] = javax.swing.JComponent with javax.accessibility.Accessible
    

    Next step would be to lift this trick to higher kinded types (not tested).
    An half baked solution consists in creating values from types (cf this answer) :

    class CommonSuper[A:Manifest, B:Manifest] {
       def make[T:Manifest] = manifest[T].erasure.newInstance.asInstanceOf[T]
       val instanceA = make[A]
       val instanceB = make[B]
       def getType = CommonSuperType(instanceA, instanceB)
    }   
    

    But I'm stuck in this unintuitive inconsistency :

    scala> val test = new CommonSuper[JButton, JPanel]
    
    scala> test.getType
    res66: Manifest[Any] = Any
    
    scala> CommonSuperType(test.instanceA, test.instanceB)
    res67: Manifest[javax.swing.JComponent with javax.accessibility.Accessible] = javax.swing.JComponent with javax.accessibility.Accessible
    

    Anyway, whereas I'm fond of this type of questions (questions about types), here it smells like an XY Problem.

提交回复
热议问题