是否可以在 Scala 的类型系统级别上找到一个通用的超类型? [英] Is it possible to find a common supertype on type-system level in Scala?

查看:38
本文介绍了是否可以在 Scala 的类型系统级别上找到一个通用的超类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否可以在 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

我自己没能找到它,但我不能使用替代方法,比如添加额外的参数,因为我必须遵循预先指定的界面.

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.

推荐答案

(不是一个完整的解决方案,但可能会提供一些想法)

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

Scala 的一个令人印象深刻的特性是它能够在将一个橙子附加到一个苹果列表时返回一个 Fruits 列表.值很好,正是因为你让泛型类型被推断出来.

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]  

它有效(有点):

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

下一步是将此技巧提升到更高级的类型(未测试).
半成品解决方案包括从类型创建值(参见 this answer):

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

无论如何,虽然我喜欢这类问题(关于类型的问题),但在这里它闻起来像XY 问题.

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

这篇关于是否可以在 Scala 的类型系统级别上找到一个通用的超类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆