1

Try to understand how I can use type in scala:

object TypeSample extends App {

  type MyParams = Map[Int, String]

  def showParams(params: MyParams) = {
    params.foreach(x => x match { case (a, b) => println(a + " " + b) })
  }

  //val params = MyParams( 1 -> "one", 2 -> "two")
  val params = Map( 1 -> "one", 2 -> "two")

  showParams(params)

}

This line throws compilation exception: "Can not resolve symbol 'MyParams'"

//val params = MyParams( 1 -> "one", 2 -> "two")

Why? I can not use 'type' like this?

om-nom-nom
  • 62,329
  • 13
  • 183
  • 228
ses
  • 13,174
  • 31
  • 123
  • 226

2 Answers2

4

Map( 1 -> "one", 2 -> "two") means Map.apply( 1 -> "one", 2 -> "two"). Map is a singleton object.

Try this:

val MyParams = Map.apply[Int, String] _
Community
  • 1
  • 1
senia
  • 37,745
  • 4
  • 88
  • 129
4

Because MyParams is only an alias to the type Map[Int, String]. To make this work, you have to add a factory like

object MyParams {
  def apply(params: (Int, String)*) = Map(params: _*)
}
drexin
  • 24,225
  • 4
  • 67
  • 81
  • I guess, it is the option to make the compiler/scala even more smarter if one make an alias to some Class, and this class has companion object with apply method in it, then alias could use this.. since alias = synonym – ses Dec 16 '12 at 22:36