Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating Objects from type alias in Scala [duplicate]

Tags:

typedef

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
}

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

like image 850
cheezsteak Avatar asked Nov 03 '14 18:11

cheezsteak


Video Answer


1 Answers

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)

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.

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.

like image 159
Travis Brown Avatar answered Sep 30 '22 15:09

Travis Brown