Scala检查ListBuffer [MyType]是否包含一个元素

时间:2019-05-24 08:47:44

标签: scala listbuffer

我有两个班级:

server {
  server_name self-hosted.com;

  listen 80;
  root /path/to/my/project;

  proxy_buffering off;

  location / {
    if ($query_string ~ debug=1) {
      rewrite ^/app.min.js$ /app.dev.js? permanent;
    }

    try_files $uri $uri/ =404;
  }
}

如何检查项目是否包含描述为x和id = y的项目?

3 个答案:

答案 0 :(得分:4)

那是

list.exists(item => item.description == x && item.id == y)

如果您还为自己的课程实现了equals(或者甚至更好,将其设置为case class,它可以自动执行此操作),则可以简化为

case class Item(description: String, id: String)
 // automatically everything a val, 
 // you get equals(), hashCode(), toString(), copy() for free
 // you don't need to say "new" to make instances

list.contains(Item(x,y))

答案 1 :(得分:1)

类似这样的东西:

def containsIdAndDescription(id: String, description: String) = {
   items.exists(item => item.id == id && item.description == description )
}

答案 2 :(得分:0)

也许也可以考虑以下方法:

//filter will return all elements which obey to filter condition

list.filter(item => item.description == x && item.id == y)

//find will return the fist element in the list

list.find(item => item.description == x && item.id == y) 
相关问题