简体   繁体   中英

How to Map with a case class in Scala

I am trying to convert, a Map with the case class I defined using the Apply.

case class ETLConfig (srcTableName:Option[String] = None, 
                  idCol:Option[String] = None , 
                  orderingCol:Option[String] = None)

object ETLConfig {
      def apply(map: Map[String, String]): ETLConfig =
        ETLConfig(map.get("srcTableName"),map.get("idCol"),map.get("orderCol"))
    }
Error:
command-512604125416347:2: error: too many arguments for method apply: (map: Map[String,String])ETLConfig in object ETLConfig
  def apply(map: Map[String, String]):ETLConfig = ETLConfig(map.get("srcTableName"),map.get("idCol"),map.get("orderCol"))

Can someone please point me the whats wrong I am doing.

Also I tried the below and is working.

val empMap:Map[String, String] = Map("srcTableName" -> "Employee","idCol" -> "EmpId", "orderCol" -> "CreatedOn" )
val empConfig = ETLConfig(dtMap.get("srcTableName"),dtMap.get("idCol"), dtMap.get("orderCol"))
val srcTable = dtConfig.srcTableName.orNull

EDIT : Since you're using Databricks, you should define your classes and objects in package cells .

Original Answer:

I assume you're doing this in a REPL. A case class and its companion object need to be in the same file. In the usual Scala REPL, each command counts as a new "file." This means that your ETLConfig object is not a companion to your case class, with the result that it shadows your apply method instead of overloading it (and you can't call the original one as a result).

In the official Scala REPL, you can solve this by using the :paste command:

scala> :paste
// Entering paste mode (ctrl-D to finish)

case class ETLConfig (srcTableName:Option[String] = None, 
                  idCol:Option[String] = None , 
                  orderingCol:Option[String] = None)

object ETLConfig {
      def apply(map: Map[String, String]): ETLConfig =
        ETLConfig(map.get("srcTableName"),map.get("idCol"),map.get("orderCol"))
    }

// Exiting paste mode, now interpreting.

defined class ETLConfig
defined object ETLConfig

From your output, it looks like you're using a different REPL, so I don't know if this will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM