Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Class alias in scala

Tags:

alias

scala

Is it possible in Scala to define MyAlias[A] as an alias for MyClass[String, A]. For example, MyAlias[Int] would refer to Map[String, Int].

like image 253
kheraud Avatar asked May 31 '12 08:05

kheraud


People also ask

What is alias in Scala?

A type alias is usually used to simplify declaration for complex types, such as parameterized types or function types. Let's explore examples of those aliases and also look at some illegal implementations of type aliases.

How do you define a class in Scala?

Defining a classThe keyword new is used to create an instance of the class. We call the class like a function, as User() , to create an instance of the class. It is also possible to explicitly use the new keyword, as new User() , although that is usually left out.

How do you use traits in Scala?

In scala, trait is a collection of abstract and non-abstract methods. You can create trait that can have all abstract methods or some abstract and some non-abstract methods. A variable that is declared either by using val or var keyword in a trait get internally implemented in the class that implements the trait.

How does Scala determine types when they are not specified?

For example, a type constructor does not directly specify a type of values. However, when a type constructor is applied to the correct type arguments, it yields a first-order type, which may be a value type. Non-value types are expressed indirectly in Scala.


1 Answers

Note that Map is a trait, not a class.

You can still alias it using the type keyword:

type StringMap[A] = Map[String, A]

val myMap: StringMap[Int] = Map("a" -> 1)

This can be done within the scope of a class, object or trait definition (and in the scope of any method or expression).

Sometimes you'll want the alias to be private to its declaring scope, purely as a convenience for your implementation code. If you want the type to be usable generally, Package Objects come in useful:

package object mypackage {
  type StringMap[A] = Map[String, A]
}

Because Map is a trait (and associated companion object) and not a class, you won't be able to use it directly to create instances:

val myMap = new StringMap[Int]
// error: trait Map is abstract; cannot be instantiated

If you alias a class, though, you can still use the new keyword:

type StringHashMap[A] = HashMap[String, A]
val myMap = new StringHashMap[Int]
like image 51
Ben James Avatar answered Oct 01 '22 18:10

Ben James