Search code examples
scalaimport

how to keep a string in class file and access it in scala?


I am keeping one string value in a class file. I want to get this string in another scala main function. How do i get the string abc in main scala code.

package integration.utils


object schemaStructure  {

  class schemaStruct {

    def schemaJson: String =
      """
                  map<
                    string,
                    struct<
                        path:string,
                        type:string,
                        optional:string,
                        defaultValue:string
                    >
                  >
                """

  }
}

Solution

  • schemaJson can now be just a val, not def.

    schemaJson seems to be just a constant now, you can reference it without instantiating a class.

    You can keep it in an object, for example lifting it a level above

    package integration.utils
    
    object schemaStructure  {
      val schemaJson: String = """..."""
    }
    
    import integration.utils.schemaStructure
    
    schemaStructure.schemaJson
    

    or

    import integration.utils.schemaStructure._
    
    schemaJson
    

    Or you can put it into companion object of class

    package integration.utils
    
    object schemaStructure  {
    
      class schemaStruct // do you need this class?
    
      object schemaStruct {
        val schemaJson: String = """..."""
      }
    }
    
    import integration.utils.schemaStructure
    
    schemaStructure.schemaStruct.schemaJson
    

    or

    import integration.utils.schemaStructure.schemaStruct._
    
    schemaJson
    

    Surely, you can keep a val in a class, then you'll have to instantiate the class like you did. Or you can put a val in a trait and extend the trait.

    Try to learn basics of Scala:

    https://docs.scala-lang.org/tour/tour-of-scala.html

    https://learnxinyminutes.com/docs/scala/