Scala class extends {}

前端 未结 3 1129
盖世英雄少女心
盖世英雄少女心 2021-01-11 14:21

By chance I came across weird compiling Scala syntax:

class Some extends {
  def hi = println(\"hi\")
}
         


        
3条回答
  •  -上瘾入骨i
    2021-01-11 14:48

    Yes this is Scala's structural typing or more commonly known as duck typing.

    object LoudDuck {
        def quack(): String = "QUACK"
    }
    
    object QuietDuck {
        def quack(): String = "quack"
    }
    
    object CowDuck {
        def quack(): String = "moo"
    }
    
    def quackMyDuck(duck: { def quack(): String }) {
        println(duck.quack())
    }
    
    scala>quackMyDuck(LoudDuck)
    QUACK
    
    scala>
    
    scala>quackMyDuck(QuietDuck)
    quack
    
    scala>
    
    scala>quackMyDuck(CowDuck)
    moo
    

    You can also declare your stuctural types with the "type" keyword.

    type Duck = { def quack(): String }
    
    def quackMyDuck(duck: Duck) {
        println(duck.quack())
    }
    

提交回复
热议问题