在 Scala 中输入别名

Type alias in Scala

我有一个任务,我应该实现一些通过类型别名操作的功能:

   /**
   * We represent a set by its characteristic function, i.e.
   * its `contains` predicate.
   */
  override type FunSet = Int => Boolean 

但我不明白这是什么意思。我们怎样才能用它的特征来表示一个集合?即,它是如何工作的?我有一个检查元素是否存在的函数:

   /**
   * Indicates whether a set contains a given element.
   */
  def contains(s: FunSet, elem: Int): Boolean = s(elem)

我不知道它检查什么?例如,我需要实现创建单调集的函数:

   /**
   * Returns the set of the one given element.
   */
  def singletonSet(elem: Int): FunSet = elem == ???

但是我不知道我应该创建什么?

你的问题很迷惑。什么是 singletonType 类型别名与单例有什么关系?

type FunType = Int => Boolean

FunType 现在只是较长正确类型的(轻微)缩写。 (它本身就是 Function1[Int,Boolean] 类型的一种方便形式。)

您可以创建该类型的值。

val isOdd: FunType = _ % 2 > 0

并且您可以创建接收该类型值的方法。

def applyTest(n: Int, f: FunType):Boolean = f(n)
applyTest(77, isOdd)  //true

等等。它只是一种类型。