在 Scala 中从类型别名创建对象 [英] Creating Objects from type alias in Scala

查看:46
本文介绍了在 Scala 中从类型别名创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何从 Scala 中的类型别名构造对象?

How can one construct an object from a type alias in scala?

type MyType = List[Int]
println(List[Int]())
println(MyType())  // error: not found: value MyType

这在必须返回该类型的新实例的函数中是有问题的.基本示例:

This is problematic in a function that must return a new instance of that type. Basic Example:

def foo(x: MyType): MyType = {
  if (x.head == 0) MyType() // Should Nil be used?
  else if (x.head == -1) new MyType(1,2,3,4)
  else x
}

foo 怎么可能不知道 MyType 的实际类型?

How can foo become unaware of the actual type of MyType?

推荐答案

Scala(和 Java 一样)对于类型和值有不同的命名空间,类型别名只是将别名引入类型命名空间.在某些情况下,您可以将别名与引用伴随对象的 val 配对以获得您正在寻找的效果:

Scala (like Java) has different namespaces for types and values, and a type alias only introduces the alias into the type namespace. In some cases you can pair the alias with a val referring to the companion object to get the effect you're looking for:

scala> case class Foo(i: Int)
defined class Foo

scala> type MyType = Foo
defined type alias MyType

scala> val MyType = Foo
MyType: Foo.type = Foo

scala> MyType(1)
res0: Foo = Foo(1)

这不适用于 List[Int],因为 List 类型和 List 伴随对象的 >apply 方法有一个类型参数,List 伴随对象本身没有.

This won't work with List[Int], though, since while both the List type and the List companion object's apply method have a type parameter, the List companion object itself doesn't.

你最好的选择是使用类似 Nil: MyType 的东西,但你会发现通常使用这样的类型别名(即作为一种缩写)通常不是最好的解决方案.

Your best bet is to use something like Nil: MyType, but you'll find that in general using type aliases like this (i.e. just as a kind of abbreviation) often isn't the best solution.

这篇关于在 Scala 中从类型别名创建对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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