Question

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?

Était-ce utile?

La solution

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: _*)
}

Autres conseils

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] _
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top