0
我認爲這是不可能的,但也許我錯過了什麼?可以將具有多條路徑的map/flatMap序列翻譯爲理解嗎?
下面是一個例子
val sentences = "hello.what is your name?I am Loïc"
sentences.split("\\.|\\?").flatMap { sentence =>
if (sentence.startsWith("h")) sentence.split(" ").map(word => word.toUpperCase)
else if (sentence.startsWith("w")) sentence.split(" ").flatMap(word => List(word.toUpperCase, "-").map(word => word.toUpperCase))
else List(sentence)
}
可以這樣被轉化爲一個換理解表達?
我注意到,當我在期貨上使用map/flatMap時(例如在webservice調用上),我需要對服務響應進行模式匹配時,我經常使用這種模式。所以我試圖提高可讀性。
謝謝:)
「理解表達」的含義是什麼?你想要將flatMap轉換爲foreach循環? – eliasah
@eliasah我的意思是這樣的{ 書< - 書籍 如果book.author startsWith 「鮑勃」 }收率book.title 可以在 books.filter(書=翻譯> book.author startsWith 「鮑勃」 ).map(book => book.title) – Loic