2012-08-30 172 views
0

我有一個斯卡拉理解unapplySeq

object radExtractor{ 
    def unapplySeq(row:HtmlTableRow):Option[List[String]]={ 
     val lista = (for{ 
     a<-row.getByXPath("td/span/a") 
     ah= a.asInstanceOf[DomNode] 
     if(ah.getFirstChild!=null) 
     } yield a.asInstanceOf[DomNode].getFirstChild.toString).toList 
     lista match{ 
     case Nil=>None 
     case l @ List(duns,companyname,address,city,postal,_bs,orgnummer, _*) =>Some(l) 
     case _ =>println("WTF");None 
     } 
    } 
    } 

,我想在一個列表理解一樣使用它:

val toReturn = for{ 
     rad<-rader 
     val radExtractor(duns,companyname,address,city,postal,_,orgnummer,_*)=rad 
} yield Something(duns,companyname,address,city,postal,orgnummer) 

但是,當「拉德」的「雷德」失敗,因爲提取返回None我收到MatchError

是不是理解提取器應該處理/忽略None案件或我只是錯過了什麼?

我能做

val toReturn = rader.collect{case radExtractor(duns,companyname,address,city,postal,_,orgnummer, _*)=> 
      Something(companyname=companyname,address=address,city=city,postalcode=postal,orgnummer=orgnummer,duns=duns.toInt) 
} 

但是,這不會被視爲性感;) 謝謝

回答

3

,因爲你在分配進行模式匹配爲val

val radExtractor(duns,companyname,address,city,postal,_,orgnummer,_*)=rad 

...比賽必須成功,否則你會遇到錯誤。上述語法在for-comprehension之外是有效的,Scala不會爲非匹配的情況提供任何特殊行爲。

要過濾掉非匹配值在一個換理解,直接使用圖案到<-的左邊:

val toReturn = for { 
    radExtractor(duns,companyname,address,city,postal,_,orgnummer,_*) <- rader 
} yield Something(duns,companyname,address,city,postal,orgnummer)