Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

types

scala

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 something with this signature:

type CommonSupertype[A, B] // can't be more specific

where these hold true: (pseudocode)

CommonSupertype[String, Int] = Any
CommonSupertype[JButton, JPanel] = JComponent

etc.

I haven't been able to find it myself, but I can't use alternatives like adding an extra parameter, since I have to follow a pre-specified interface.

like image 907
Anonymous Avatar asked Nov 04 '11 20:11

Anonymous


1 Answers

(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.

like image 149
YvesgereY Avatar answered Nov 15 '22 22:11

YvesgereY