模式匹配Scala中的列表[_]

时间:2017-05-15 15:57:30

标签: scala pattern-matching type-erasure

我有以下代码

Office.context.ui.messageParent(JSON.stringify(msg));

当我将List Of Maps和String传递给这个函数时,它只保持打印第一个case语句,而不是第二个case语句。有什么我做错了吗?

2 个答案:

答案 0 :(得分:2)

以下草图(类型取决于您的用法):

def f[T](obj : List[T], trans : T => String) = obj.map(trans).mkString

然后按以下方式致电f

scala> f[Map[Int,Int]](List(Map(1->2, 3->4), Map(0->0)), _.toList.map( x => (x._1 - x._2).toString).mkString(","))
res5: String = -1,-10

scala> f[String](List("abc","def","ghi"), x => x.reverse)
res6: String = cbafedihg

答案 1 :(得分:2)

原因是它们都是List(该功能只是检查outer dataType并忽略inner dataType。 您可以根据需要使用以下解决方案,并根据需要进行修改。

 def function(obj: Any) : Unit = {
   Try {
     obj.asInstanceOf[List[Map[String, Any]]].map(function2(_))
     println("ListMap")
   }getOrElse (
     Try{
        obj.asInstanceOf[List[String]].map(function2(_))
        println("List of String")
     }getOrElse
       println("do nothing")
     )
 }

function2必要的原因是,如果transformation casted datatype无法识别,则transformation无法识别。您传递给function的数据中需要一些 def function2(obj: Any) = obj match { case _ : Map[String, Any] => //do what you want with your map case _ : String => //do what you want with your string list case _ => // this is not done for now }

import scrapy

class PdgaSpider(scrapy.Spider):
name = "pdgavideos"
start_urls = ["http://www.pdga.com/videos/"]

def parse(self, response):
    for link in response.xpath('//td[2]/a/@href').extract():
        yield scrapy.Request(response.urljoin(link), 
callback=self.parse_page)

    # If page contains link to next page extract link and parse
    next_page = response.xpath('//a[contains(., 
"Go\s+to\s+page\s+2")]/@href').extract_first()

    if next_page:
        yield scrapy.Request(response.urljoin(next_page), 
callback=self.parse)

# Youtube link 1st pass

def parse_page(self, response):

    link = response.xpath('//iframe/@src').extract_first()
    linkprune = link.split('/embed/')[+1]
    output = linkprune.split('?')[0]

    yield{
         'https://www.youtube.com/watch_videos?video_ids=': output + ','
    }

我希望这正是你要找的东西