scala - 我可以有一个带有默认/硬编码值的案例类吗
问题描述
例如,假设我有一个密封特征 AnimalSounds,我有一个案例类“Dog”和一个案例类“Cat”我希望这两个案例类的值默认为“Woof”和“Cat”
sealed trait AnimalSounds extends Product with Serializable
final case class Dog(sound: String = "woof") extends AnimalSounds
final case class Cat(sound: String = "meow") extends AnimalSounds
println(Dog.sound)
我收到错误“声音不是对象的成员”
解决方案
如果通过“硬编码”表示常量考虑case objects
如下
sealed trait AnimalSounds { val sound: String }
case object Dog extends AnimalSounds { val sound = "woof" }
case object Cat extends AnimalSounds { val sound = "meow" }
Dog.sound
哪个输出
res0: String = woof
推荐阅读
- c# - 如何使用 Cefsharp 管理多用户配置文件?
- laravel-5 - Laravel:抛出新的 MethodNotAllowedHttpException($others);
- python - Python中的master-workers实现
- java - 仅将法语口音转换为百分比编码
- java - 我如何将 java java.nio.ByteBuffer 转换为 spring org.springframework.web.multipart.MultipartFile?
- c# - Combobox : 每个 DataTrigger 的 DataTemplate
- python-3.x - 如何在python中操作字符串?或者如何在python中获取子字符串?
- python - 读取txt文件,每次读取两个十六进制数,实现自动读取下一行,并写入数据到列表中
- java - Android Webview 有时无法呈现 pdf,而是显示空白/白页
- python - 如何删除python中的关键字?