Echo
Echo

Reputation: 3049

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 !

Upvotes: 0

Views: 278

Answers (2)

Rogach
Rogach

Reputation: 27250

Also you can try creating it like this:

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

The resulting type would be CarObject.

Upvotes: 2

kiritsuku
kiritsuku

Reputation: 53358

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.

Upvotes: 4

Related Questions