鑑於此代碼:斯卡拉與方法的構造類型,其中只有一些PARAMS已知
object Testy extends App {
case class Person(
id: Option[Long],
firstName: String,
lastName: String,
address: Address)
case class Address(id: Option[Long],
name: String,
number: Int)
val personOrAddress:AnyRef= Person(Some(1L), "first", "last", Address(Some(1L), "street", 1))
type HasCopyMethodWithId = _
val newId = Some(123L)
personOrAddress.asInstanceOf[HasCopyMethodWithId].copy(id = newId)
}
我怎樣才能實現「類型HasCopyMethodWithId」,讓這個代碼編譯和運行時不會失敗?
我試着:
type HasCopyMethodWithId = {def copy(id: Option[Long]): AnyRef}
我認爲你不能,這些複製方法是不同的。您將不得不創建另一種方法,如使用副本的'copyId'。 –
是否可以通過宏檢測實際類型(不是一般結構類型)? – eirirlar