When to use case class or regular class

前端 未结 6 1797
忘掉有多难
忘掉有多难 2020-12-24 10:43

I have some misunderstanding in what cases I should use case class or regular class following by best practices. I have already read about differences of both classes but ca

6条回答
  •  时光取名叫无心
    2020-12-24 11:24

    Case Classes are normal classes with syntactic sugar. So there is no real big difference, you can do everything with a case class you can do with a class and vice versa.

    Case classes just save you a lot of boiler plate code to write.

    Perfect fit, as the name suggests, is the use of case classes in pattern matching with case.

    case class MyCase(name: String, age: Int)
    
    data : List[MyCase] = ...
    
    data foreach { 
        case MyCase(_, age) if age > 21 => println("old enough")
        case MyCase("fred", _ ) => println("Got you")
        case _ => ...
    }
    

提交回复
热议问题