2017-07-26 56 views
0

布爾值,我認爲Scala是第一語言,我已經遇到在以下不工作:添加在斯卡拉

true + true 
// Name: Compile Error 
// Message: <console>:32: error: type mismatch; 
// found : Boolean(true) 
// required: String 
//  true + true 
//    ^
// StackTrace: 

有人能解釋這個錯誤?爲什麼地球上有String

另外,在Scala中積累Boolean值的規範方法是什麼?我是否需要將它們轉換爲Int /有沒有辦法將+重載以使其按預期工作?

+2

根據你最後一個問題(「是否有一種方法來重載'+'」) - 請參閱https://stackoverflow.com/questions/2633719/is-there-an-easy-way-to-convert-a-布爾到整數 –

+2

「添加」布爾值的預期行爲是什麼? –

+0

Tzach已經發布了SO問題,以查看哪些可以回答您的問題。您需要使用'import scala.language.implicitConversions'進行BoolToInteger轉換。 - http://docs.scala-lang.org/tutorials/tour/implicit-conversions.html – prayagupd

回答

3

「String」涉及的原因是從布爾到字符串的隱式轉換,它允許編寫像"text " + true(其求值爲text true)的表達式。

您可以創建一個類似的隱式轉換從BooleanInt,如建議在here

implicit def bool2int(b:Boolean) = if (b) 1 else 0 

請注意,現在你有兩個隱式轉換,從布爾,這可能會有點棘手:

// without bool2int implicit conversion: 
scala> true + true 
<console>:12: error: type mismatch; 
found : Boolean(true) 
required: String 
     true + true 
      ^

// conversion to String works: 
scala> true + " text" 
res1: String = true text 

scala> "text " + true 
res2: String = text true 

// now we add bool2int: 
scala> implicit def bool2int(b:Boolean) = if (b) 1 else 0 
bool2int: (b: Boolean)Int 

// which makes this work: 
scala> true + true 
res3: Int = 2 

// BUT! now this conversion will be picked up because Int has a `+` method: 
scala> true + " text" 
res4: String = 1 text // probably not what we intended! 

// This would still work as before: 
scala> "text " + true 
res5: String = text true 
+1

更準確地說,'「文本」+ true'不需要轉換,'true +「文本可以。 –

1

您可以使用隱式轉換。當編譯器發現表達式類型錯誤時,它將查找隱式函數。 創建隱式函數時,編譯器會在每次發現布爾值時調用它,但在上下文中需要Int。

import scala.language.implicitConversions 
implicit def toInt(v:Boolean):Int = if (v) 1 else 0 

要看看它是如何工作的,讓我們添加一個print語句

implicit def toInt(v:Boolean):Int = { 
println (s"Value: $v") 
if (v) 1 else 0 
} 

輸出:

scala> val x = false 
x: Boolean = false 

scala> val y = true 
y: Boolean = true 

scala> x 
res6: Boolean = false // No implicit function called. 

scala> x + y 
Value: false // Implicit function called for x. 
Value: true // Implicit function called for y. 
res5: Int = 1 

所以當布爾是發現和詮釋在上下文中需要調用此函數,但不以其他方式。