2015-10-04 94 views
2

我使用IntelliJ IDEA的Scala插件,並且發現該插件的奇怪行爲。讓我告訴你一個代碼片段:IntelliJ IDEA:檢測不能是相同類型的表達式的比較(==和!=)

def fun: Option[Any] => Int = { 
    case Some(x) if x.isInstanceOf[Int] => x.asInstanceOf[Int] 
    case None => 0 
} 

關於Scala代碼,IDEA給我一個警告:

Comparing unrelated types 
Detects comparisons (== and !=) of expressions which cannot be the same type 

和它突出的下一條語句x.isInstanceOf[Int]。我只使用isInstanceOf運算符來確定x的類型。這是插件的錯誤還是我錯過了Scala語法中的某些東西?

+0

你想,如果個數爲int然後返回其他數字0? –

+0

是的,我想通過模式匹配來做到這一點。 – Finkelson

+0

根據我的經驗,IntelliJ IDEA的「比較無關類型」警告是不可靠的。我在幾個地方看到了這些警告是錯誤的。 –

回答

0

使用getOrElse(0)進行此操作。

編輯:

您歌廳此錯誤的一些(x)是不一樣的詮釋。
但你正在狀態這裏指揮過的一些(x)的第一,然後直接檢查實例是否爲int的,所以他們基本上沒有相同的類型(INT和一些)
case Some(x) if x.isInstanceOf[Int] => x.asInstanceOf[Int]

爲了避免這種情況警告:
如果您想將其保存爲Option [Any]作爲輸入,則可以執行此類操作。

def fun(x:Option[Any]):Int = x match { 
    case x:Some[Int] => x.get 
    case x => 0 
} 

否則,如果你知道的輸入將是選項[INT]然後 用它作爲參數。

def fun(x:Option[Int]):Int = x match { 
    case x:Some[Int] => x.get 
    case None => 0 
} 
+0

好點!但我想用一個'Constructor Pattern'。我有一個懷疑,有一些解決方法,以使其正確。 – Finkelson

+0

@Finkelson:試試這個..'def fun:Option [Any] => Int = {0} => x.asInstanceOf [Int] case None => 0 }' –

+0

Yeap,the警告已經消失。 – Finkelson

0

我沒有得到類似的警告,但很重要的東西,你應該知道的是,你的代碼是不是「case語句」完整的,具有潛在的漏洞。例如,你應該傳遞一些(「字符串」),你的案例行都不能處理這個問題。潛在的修正:

def fun: Option[Any] => Int = { 
    case Some(x) => if (x.isInstanceOf[Int]) x.asInstanceOf[Int] else 0 
    case None => 0 
} 

def fun: Option[Any] => Int = { 
    case Some(x) if x.isInstanceOf[Int] => x.asInstanceOf[Int] 
    case Some(other) => 0 
    case None => 0 
} 
+0

我增加了一個case'case Some(other)=> 0',但我仍然看到IDEA警告。 – Finkelson