27
votes

How can I define type in Scala? Like

type MySparseVector = [(Int, Double)]

in Haskell or

typedef MySparseVector = std::list<std::pair(int, double)>> 

in C++?

I tried

type MySparseVector = List((Int, Double))

but can't figure how to make it work. If I write this in the beginning of class file I got "Expected class or object definition" error.

PS Sorry, I mistyped. I tried to use List[(Int, Double)] in Scala.

1

1 Answers

43
votes
type MySparseVector = List[(Int, Double)]

Example usage:

val l: MySparseVector = List((1, 1.1), (2, 2.2))

Types have to be defined inside of a class or an object. You can import them afterwards. You can also define them within a package object - no import is required in the same package, and you can still import them into other packages. Example:

// file: mypackage.scala
package object mypackage {
  type MySparseVector = List[(Int, Double)]
}

//in the same directory:
package mypackage
// no import required
class Something {
  val l: MySparseVector = Nil
}

// in some other directory and package:
package otherpackage
import mypackage._
class SomethingElse {
  val l: MySparseVector = Nil
}