Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
276 views
in Technique[技术] by (71.8m points)

override case class method in scala

I am trying to override a method of trait in my case class which want to display all the members of case class. I am using it for debugging purpose.

trait A{
   def myMethod(employee:Emp):Unit
}

case class Emp(id:String,name:String) extends A {
   override def myMethod(employee: Emp): Unit = 
              emp.productIterator.toList.foreach(println)
}

other possible way to do this is

    emp.productIterator.toList.mkString("
")

to declare Emp("10","abc"). I am new to Scala, not sure how to call the override method of trait.

  1. I am not sure if any other generic way to achieve this functionality to get string form of case class members.

  2. Efficient way to use trait and case class to achieve this functionality.I want to understand how apply method and companion objects can be implemented .

  3. I want to implement logging instead of using println. Can anyone suggest a tutorial for it?
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Previous answer was because i didn't understood your question right. This should answer your question:

If you want this only for debugging purposes you can use it like that:

trait A{
  def myMethod(employee:Emp):Unit
}

case class Emp(id:String,name:String) extends A {
  override def myMethod(employee: Emp): Unit =
    this.productIterator.toList.foreach(println)
}

Emp("1", "2").myMethod(None.orNull)

But more logical would be to use object with this nonGeneric method:

case class Emp(id:String,name:String)

object A{
  def myMethod(employee: Emp):Unit = {
    employee.productIterator.toList.foreach(println)
  }
}

A.myMethod(Emp("1", "2"))

For logging purposes you can use just apache log4j


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...