您好,我有以下内容:
trait CarObject{
val name: String
}
def takeCarObject(obj:CarObject)
我怎样才能准备一个特征对象CarObject,并将其传递给方法?
我试过了:
private def createCarObject(str:String)= new CarObject {val name = STR}
但结果不是CarObject!
答案 0 :(得分:4)
这确实有效:
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
注意:如果您没有为方法显式设置返回值,则会推断返回值java.lang.Object with XXX
,在这种情况下,XXX为CarObject
。
答案 1 :(得分:2)
您也可以尝试这样创建:
(new CarObject { val name = str}):CarObject
结果类型为CarObject
。