简体   繁体   English

Scala 中的简单隐式转换

[英]Simple implicit conversions in Scala

I'm pretty new to scala and I really love it so far but I'm stuck with a really weird problem.我是 scala 的新手,到目前为止我真的很喜欢它,但我遇到了一个非常奇怪的问题。 I wanted to try implicit conversions by implementing D&D-style dice expressions.我想通过实现 D&D 风格的骰子表达式来尝试隐式转换。 ie 2d12 "throw two twelve-sided dice"... you know what I mean.即 2d12“掷两个十二面骰子”......你知道我的意思。

From what I understand scala should be able to compile this据我了解 scala 应该可以编译这个

(1 d 6).roll

and probably even this甚至可能是这个

1d6 + 2 - 1d30

but I get a "value d is not a member of int" compile error in my specs test.但是我在我的规格测试中得到了一个“value d is not a member of int”的编译错误。

package meh.toast
import scala.util.Random

object Dice {
  class DiceSymbol(val amount:Int) {
    def d(sides:Int):Dice = new Dice(amount, sides)
  } 

  implicit def int2DiceSymbol(amount:Int) = new DiceSymbol(amount)
  implicit def dice2Int(d:Dice) = d.roll

  private val rnd = new Random()
  protected def throwDice(sides:Int) = rnd.nextInt(sides) + 1
}

class Dice(amount:Int, sides:Int) {
   def roll:Int = (1 to amount) map { _ => Dice.throwDice(sides)} sum 
}

I'm really stuck.我真的卡住了。 It would be awesome if you could help, it's probably something really simple.如果您能提供帮助,那就太好了,这可能真的很简单。

Thanks in advance提前致谢

You're really close: but you have to make sure the implicit functions from the Dice object are in scope when you try to use them:你真的很接近:但是当你尝试使用它们时,你必须确保来自Dice object 的隐式函数在 scope 中:

 scala> import Dice._
 import Dice._

 scala> (1 d 6).roll
 res12: Int = 2

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM