開発環境
- macOS Mojave - Apple (OS)
- Windows 10 Pro (OS)
- IntelliJ IDEA CE(Community Edition) (IDE(統合開発環境))
- Kotlin (プログラミング言語)
Head First Kotlin: A Brain-Friendly Guide (Dawn Griffiths(著)、David Griffiths(著)、O'Reilly Media)のChapter 11(lambdas and higher-order functions - Treating Code Like Data)、Code Magnets(356)の解答を求めてみる。
コード
data class Grocery( val name: String, val category: String, val unit: String, val unitPrice: Double ) fun search(list: List<Grocery>, criteria: (g: Grocery) -> Boolean) { for (l in list) { if (criteria(l)) { println(l.name) } } } fun main() { val groceries = listOf( Grocery("Tomatoes", "Vegetable", "lb", 3.0), Grocery("Mushrooms", "Vegetable", "lb", 4.0), Grocery("Bagels", "Bakery", "Pack", 1.5), Grocery("Olive oil", "Pantry", "Bottle", 6.0), Grocery("Ice cream", "Frozen", "Pack", 3.0) ) println("Expensive ingredients:") search(groceries) { i: Grocery -> i.unitPrice > 5.0 } println("All vegetables:") search(groceries) { i: Grocery -> i.category == "Vegetable" } println("All packs:") search(groceries) { i: Grocery -> i.unit == "Pack" } }
入出力結果
Expensive ingredients: Olive oil All vegetables: Tomatoes Mushrooms All packs: Bagels Ice cream Process finished with exit code 0
0 コメント:
コメントを投稿