简体   繁体   English

如何在Scala中找到超类型

[英]How to find supertype in scala

If A<:B, I understand that means A is a subtype and B a supertype, I thought I use A in place of B anywhere B is needed because it has inherited all of its properties from B. Now here is my problem 如果A <:B,我知道这意味着A是子类型,而B是超类型,我以为在需要B的任何地方都用A代替B,因为它继承了B的所有属性。这是我的问题

type One
type Two
type Three
type Four
type Five
type Six
type Seven
type Eight

type Fun1 = { val a: One } => { val b: Two }
type Fun2 = { val b: Two } => { val a: One }

type SuperType = {
??
}

type TypeOne = {
  def apply: { val func: Fun1 ; val c: Three } => { val b: Two ; val d: Four }
  val g: Seven
}

type TypeTwo = {
  def apply: { val func: Fun2 ; val e: Five } => { val b: Two ; val f: Six }
  val h: Eight
}

How can I make SuperType which is the supertype of TypeOne and TypeTwo. 我如何使SuperType成为TypeOne和TypeTwo的超类型。 I could only come up with the keyword 'Any' nothing else works. 我只能拿出关键字“ Any”来解决。 I also tried 我也试过

def apply: {val func: Fun1}=>{val b: Two}

because I don't see and relationship between all the other values 因为我看不到所有其他值之间的关系

Here's one way to get the relationships you want. 这是获得所需关系的一种方法。

abstract class SuperType
class TypeOne extends SuperType { /* your code here */ }
class TypeTwo extends SuperType { /* etc. */ }

The type keyword is mostly used to make a type alias or declare an abstract type the will be concretely defined later on, somewhere down the chain of hierarchy. type关键字通常用于创建类型别名或声明抽象类型,稍后将在层次结构链中的某个位置对其进行具体定义。 As it is, the code you've posted doesn't really create anything. 实际上,您发布的代码并没有真正创建任何东西。 You can't instantiate objects of any of those types. 您不能实例化任何这些类型的对象。

BTW, if that's what you're trying to do, declare an abstract type relationship, then something like this, type TypeOne <: SuperType , is what you want. 顺便说一句,如果这是您要执行的操作,请声明一个抽象类型关系,然后按如下所示type TypeOne <: SuperType

Maybe this isn't what you're looking for, but does this work for you? 也许这不是您要找的东西,但这对您有用吗?

sealed trait SuperType
trait TypeOne extends SuperType {
  def apply: { val func: Fun1 ; val c: Three } => { val b: Two ; val d: Four }
  val g: Seven
}

trait TypeTwo extends SuperType {
  def apply: { val func: Fun2 ; val e: Five } => { val b: Two ; val f: Six }
  val h: Eight
}

The only possible relationship I see between Fun1 and Fun2 is that they're both functions, so I guess SuperType is a function with generic arguments. 我看到的Fun1Fun2之间唯一可能的关系是它们都是函数,因此我猜SuperType是具有通用参数的函数。 I tried to stick as much as possible to the style you exposed in your snippet (although Scala offers much more idiomatic ways to define type hierarchies). 我试图尽可能地坚持您在代码片段中公开的样式(尽管Scala提供了更多惯用的方式来定义类型层次结构)。

type SuperType = {
  type A
  type B
  def apply: { val a: A } => { val b: B }
}

type Fun1 <: SuperType {
  type A = One
  type B = Two
}
type Fun2 <: SuperType {
  type A = Two
  type B = One
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM