freechipsproject / chisel-bootcamp

Generator Bootcamp Material: Learn Chisel the Right Way
Apache License 2.0
982 stars 278 forks source link

Chapter 3.6 - companion object for Mac: solution for apply(..) is not a Factory method #159

Closed wunderabt closed 3 years ago

wunderabt commented 3 years ago

My understanding of scala companion objects is that they provide a factory method apply that returns an instance of the class. However the solution in Chapter 3.6 merely says a * b + c which is not an instance of class Mac. Instead it's code duplication of the Mac constructor.

I would have expected something like

object Mac {
    def apply[T <: Data : Ring](a: T, b: T, c: T): T = {
        var m = new Mac(chiselTypeOf(a), ???)
        m.io.a := a
        m.io.b := b
        m.io.c := c
        m
    }
}

However, I don't know how to derive the genOut type. What am I missing?

edwardcwang commented 3 years ago

A Scala apply method doesn't have to return a specific type. You can have it return an object of any type.

wunderabt commented 3 years ago

Yep, I guess I was primed by Chapter 3.5 that this was meant to be a companion object to the Mac class. But maybe that wasn't the intention here. Reading it again, it doesn't say to implement it as a companion object. So I guess I just made the connection to companion objects even when it wasn't asked for here. (or I'm still lacking in understanding of the way companion objects work)