简体   繁体   中英

How could I overload trait variable

Hello I have the follwong :

trait CarObject{ 
 val name: String
}

def takeCarObject(obj:CarObject)

How could I prepare a trait object ,CarObject, and pass it to the method ?

I have tried :

private def createCarObject(str: String) = new CarObject { val name = str}

but the result is n't a CarObject !

This does work:

scala> trait CarObject { val name: String }
defined trait CarObject

scala> def createCarObject(str: String) = new CarObject { val name = str }
createCarObject: (str: String)java.lang.Object with CarObject

scala> def createCarObject(str: String): CarObject = new CarObject { val name = str }
createCarObject: (str: String)CarObject

scala> val c = createCarObject("bmw")
c: CarObject = $anon$1@5143c423

scala> c.name
res0: String = bmw

Notice: If you don't explicitly set a return value to the method, the return value java.lang.Object with XXX is inferred, where in this case XXX is CarObject .

Also you can try creating it like this:

(new CarObject { val name = str}):CarObject

The resulting type would be CarObject .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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