1

I'm pretty new to scala and I really love it so far but I'm stuck with a really weird problem. I wanted to try implicit conversions by implementing D&D-style dice expressions. i.e. 2d12 "throw two twelve-sided dice" ... you know what I mean.

From what I understand scala should be able to compile this

(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.

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

5
  • aaand I already fixed it myself ... I didn't import all the right packages .... for this Example to work you've got to import not only the packages meh.toast._ but also meh.toast.Dice._ from where you're using it. Commented Apr 10, 2012 at 23:50
  • and I found out one more thing (for me and the other scala noobs) ... 1 d 6 must be <= 6 works fine but 1d6 doesn't. That is because 1d would convert the int literal to a double and the compiler doesn't know what to make of the 6. So in real life "d" wouldn't be a very good choice for an operator name. "!" works great! can do 1!6 +2 Commented Apr 11, 2012 at 0:03
  • Just be careful: The ! is already used as the operator for sending a message to a Scala actor. I made good experience with first making the framework work without a DSL (as in, Die(1, 6)), and add the pimp DSL later, as a refinement. Commented Apr 11, 2012 at 12:30
  • That's true! And there may be even another implicit conversion with the ! defined leading to weird results if I get that right. I don't think an integer literal can also be an actor but I might be wrong. But as I said, I was only trying here :) I used ! only because it was 2:30 AM and it was the first that came to my mind ;) Thank you guys very much! Commented Apr 11, 2012 at 15:09
  • You're welcome. Btw: Only subtypes of Actor are actors. :-) Commented Apr 11, 2012 at 22:24

1 Answer 1

3

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:

 scala> import Dice._ import Dice._ scala> (1 d 6).roll res12: Int = 2 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.