Scala App val initialization in main method

后端 未结 2 857
说谎
说谎 2021-02-07 04:23

I have some code:

object Main extends App
{
    val NameTemplate = \"\"\"^([A-Za-z]+)_(\\d+)\\.png\"\"\".r

    override def main (args:Array[String])
    {
             


        
2条回答
  •  失恋的感觉
    2021-02-07 04:49

    If you are using App trait, then you don't need to override main method - just write your code in the body of the object:

    object Main extends App {
        val NameTemplate = """^([A-Za-z]+)_(\d+)\.png""".r
    
        println(NameTemplate)
    
        val NameTemplate(name, version) = args(0)
    
        println(name + " v" + version)
    
    }
    

    It works because App trait extends DelayedInit trait which has very special initialization procedure. You can even access arguments with args, as shown in the example.

    You still need to write main method if you don't want to extend App, but in this case it will work as expected:

    object Main {
        val NameTemplate = """^([A-Za-z]+)_(\d+)\.png""".r
    
        def main(args: Array[String]) {
            println(NameTemplate)
    
            val NameTemplate(name, version) = args(0)
    
            println(name + " v" + version)
        }
    
    }
    

提交回复
热议问题