Groovy def l = [1, 2, 3] as BlockingQueue

前端 未结 3 1469
眼角桃花
眼角桃花 2021-01-28 01:46

If I write something like def l = [1, 2, 3] as Socket which is obviously nonsense, I get this:

org.codehaus.groovy.runtime.typehandling.GroovyCastE         


        
3条回答
  •  闹比i
    闹比i (楼主)
    2021-01-28 02:22

    why am I able to cast the list to BlockingQueue without error despite the fact that it fails (l doesn't end up being an BlockingQueue instance)?

    Why are you so sure that l is not a BlockingQueue instance? The following (which you can run in the Groovy console) indicates that it is a BlockingQueue instance:

    import java.util.concurrent.BlockingQueue
    
    // this assignment would be impossible if l is not a BlockingQueue
    BlockingQueue l = [1, 2, 3] as BlockingQueue
    
    // this assertion would throw an exception if l is not a BlockingQueue
    assert l instanceof BlockingQueue
    

    FYI, you can remove a lot of uncertainty about types by defining the types of your variables, rather than using def.

提交回复
热议问题