Value classes introduce unwanted public methods

前端 未结 5 2277
孤街浪徒
孤街浪徒 2021-02-19 03:44

Looking at some scala-docs of my libraries, it appeared to me that there is some unwanted noise from value classes. For example:

implicit class RichInt(val i: In         


        
5条回答
  •  情歌与酒
    2021-02-19 04:26

    I'm not sure it's "unwanted noise" as I think you will almost always need to access the underlying values when using your RichInt. Consider this:

    // writing ${r} we use a RichInt where an Int is required
    scala> def squareMe(r: RichInt) = s"${r} squared is ${r.squared}"
    squareMe: (r: RichInt)String
    
    // results are not what we hoped, we wanted "2", not "RichInt@2"
    scala> squareMe(2)
    res1: String = RichInt@2 squared is 4
    
    // we actually need to access the underlying i
    scala> def squareMeRight(r: RichInt) = s"${r.i} squared is ${r.squared}"
    squareMe: (r: RichInt)String
    

    Also, if you had a method that adds two RichInt you would need again to access the underlying value:

    scala> implicit class ImplRichInt(val i: Int) extends AnyVal {
         |   def Add(that: ImplRichInt) = new ImplRichInt(i + that) // nope...
         | }
    :12: error: overloaded method value + with alternatives:
      (x: Int)Int 
      (x: Char)Int 
      (x: Short)Int 
      (x: Byte)Int
     cannot be applied to (ImplRichInt)
             def Add(that: ImplRichInt) = new ImplRichInt(i + that)
                                                            ^
    
    scala> implicit class ImplRichInt(val i: Int) extends AnyVal {
         |   def Add(that: ImplRichInt) = new ImplRichInt(i + that.i)
         | }
    defined class ImplRichInt
    
    scala> 2.Add(4)
    res7: ImplRichInt = ImplRichInt@6
    

提交回复
热议问题