2017-07-26 55 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 

所以当布尔是发现和诠释在上下文中需要调用此函数,但不以其他方式。