简体   繁体   中英

How do I change this code to be functional programming in scala?

I'm new to functional programming and as I'm reading this book. It basically says that if you code contains "var" it means that you're still doing in a imperative way. I'm not sure how do I change my code to be functional way. Please suggests.

So basically what this code does is to processText some text and use regular expression to extract a particular text from "taggedText" and add that to a list and convert the list to json.


    val text = params("text")
    val pattern = """(\w+)/ORGANIZATION""".r

    var list = List[String]()
    val taggedText = processText(text)
    pattern.findAllIn(taggedText).matchData foreach {
      m => list ::= m.group(1)
    }

    pretty(render(list)) // render to json

Try replacing the middle section with

val list = pattern.findAllIn(taggedText).matchData.map(m => m.group(1)).toList

You can write m => m.group(1) as _.group(1) if you want.

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