在scala中生成随机对象

webghufk  于 2021-05-27  发布在  Spark
关注(0)|答案(1)|浏览(417)

我是scala的初学者,我尝试在scala中生成event fruits sales并将结果存储在json文件中。为此,我尝试生成随机对象(带有名称和来源的水果),但我遇到了困难,我不知道如何使用random类。
这是我的密码:

import scala.util.Random
import org.apache.spark.sql.SparkSession

val spark = SparkSession
.builder
.appName("FruitSales")
.getOrCreate()

object FruitSales extends Enumeration {

object Fruit extends Enumeration {
   type Fruit= Value
   val apple, banana , orange, strawberry  = Value
}

object Origin extends Enumeration {
   type Origin = Value
   val USA, espagne, france, sweden, mexico= Value
}

class Fruits(Fruit: String, Origin: String) extends Enumeration {}

def producing_events (fruit: Fruits): Fruits = {
   val rand = new scala.util.Random
   rand.nextString(200)
}

val df = spark.read.json("/tmp/file.json")

df.show(false)

}
xiozqbni

xiozqbni1#

我建议在这种情况下避免列举,没有最佳做法。这是我的方法,不完美,但会给你一个大致的想法。下面的代码生成10个随机对象,如果你真的想,你甚至可以自定义scalacheck中的概率分布,但我猜这在你的情况下太多了。

import org.scalacheck._

    final case class Fruit(name: String, origin: String)
    val originGen = Gen.oneOf( List("apple", "banana", "orange", "strawberry") )
    val fruitNameGen = Gen.oneOf( List("USA", "Espagne", "France", "Sweden", "Mexico") )

    val fruits = {
      for {
        _ <- 0 to 10
        origin <- originGen.sample.take(1)
        fruit <- fruitNameGen.sample.take(1)
      } yield Fruit(fruit, origin)
    }

    println( fruits )

还可以对对象生成添加一些限制和依赖项。只需把文档翻出来,了解更多细节。
https://github.com/typelevel/scalacheck/blob/master/doc/userguide.md

相关问题